import React from "react";
import { useQuery } from "@tanstack/react-query";
import { base44 } from "@/api/base44Client";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import InvoiceDetailView from "@/components/invoices/InvoiceDetailView";
import InvoiceExportPanel from "@/components/invoices/InvoiceExportPanel";
import { Button } from "@/components/ui/button";
import { ArrowLeft } from "lucide-react";

export default function InvoiceDetail() {
  const navigate = useNavigate();
  const urlParams = new URLSearchParams(window.location.search);
  const invoiceId = urlParams.get('id');

  const { data: user } = useQuery({
    queryKey: ['current-user-invoice-detail'],
    queryFn: () => base44.auth.me(),
  });

  const { data: invoices = [], isLoading } = useQuery({
    queryKey: ['invoices'],
    queryFn: () => base44.entities.Invoice.list(),
  });

  const { data: businesses = [] } = useQuery({
    queryKey: ['businesses-for-invoice'],
    queryFn: () => base44.entities.Business.list(),
  });

  const invoice = invoices.find(inv => inv.id === invoiceId);
  const business = businesses.find(b => 
    b.business_name === invoice?.business_name || 
    b.business_name === invoice?.hub
  );
  const userRole = user?.user_role || user?.role;

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="w-16 h-16 border-4 border-[#0A39DF] border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-slate-600">Loading invoice...</p>
        </div>
      </div>
    );
  }

  if (!invoice) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <p className="text-xl font-semibold text-slate-900 mb-4">Invoice not found</p>
          <Button onClick={() => navigate(createPageUrl('Invoices'))}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            Back to Invoices
          </Button>
        </div>
      </div>
    );
  }

  return (
    <>
      <div className="fixed top-20 left-4 z-50 print:hidden">
        <Button 
          variant="outline" 
          onClick={() => navigate(createPageUrl('Invoices'))}
          className="bg-white shadow-lg"
        >
          <ArrowLeft className="w-4 h-4 mr-2" />
          Back
        </Button>
      </div>
      <div className="flex gap-6 p-4 md:p-8">
        <div className="flex-1">
          <InvoiceDetailView invoice={invoice} userRole={userRole} />
        </div>
        <div className="w-80 flex-shrink-0 print:hidden">
          <InvoiceExportPanel invoice={invoice} business={business} />
        </div>
      </div>
    </>
  );
}