import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { FileText, Plus, Search, Eye, AlertTriangle, CheckCircle, Clock, DollarSign, Edit } from "lucide-react";
import { format, parseISO, isPast } from "date-fns";
import PageHeader from "@/components/common/PageHeader";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import AutoInvoiceGenerator from "@/components/invoices/AutoInvoiceGenerator";
import CreateInvoiceModal from "@/components/invoices/CreateInvoiceModal";

const statusColors = {
  'Draft': 'bg-slate-500 text-white',
  'Pending Review': 'bg-amber-500 text-white',
  'Approved': 'bg-green-500 text-white',
  'Disputed': 'bg-red-500 text-white',
  'Under Review': 'bg-orange-500 text-white',
  'Resolved': 'bg-blue-500 text-white',
  'Overdue': 'bg-red-600 text-white',
  'Paid': 'bg-emerald-500 text-white',
  'Reconciled': 'bg-purple-500 text-white',
  'Cancelled': 'bg-slate-400 text-white',
};

export default function Invoices() {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState("all");
  const [searchTerm, setSearchTerm] = useState("");
  const [showCreateModal, setShowCreateModal] = useState(false);

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

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

  const userRole = user?.user_role || user?.role;

  // Auto-mark overdue invoices
  React.useEffect(() => {
    invoices.forEach(async (invoice) => {
      if (invoice.status === "Approved" && isPast(parseISO(invoice.due_date))) {
        try {
          await base44.entities.Invoice.update(invoice.id, { status: "Overdue" });
        } catch (error) {
          console.error('Failed to mark invoice as overdue:', error);
        }
      }
    });
  }, [invoices]);

  // Filter invoices based on user role
  const visibleInvoices = React.useMemo(() => {
    if (userRole === "client") {
      return invoices.filter(inv =>
        inv.business_name === user?.company_name ||
        inv.manager_name === user?.full_name ||
        inv.created_by === user?.email
      );
    }
    if (userRole === "vendor") {
      return invoices.filter(inv =>
        inv.vendor_name === user?.company_name ||
        inv.vendor_id === user?.vendor_id
      );
    }
    return invoices;
  }, [invoices, userRole, user]);

  const getFilteredInvoices = () => {
    let filtered = visibleInvoices;

    if (activeTab !== "all") {
      const statusMap = {
        'pending': 'Pending Review',
        'approved': 'Approved',
        'disputed': 'Disputed',
        'overdue': 'Overdue',
        'paid': 'Paid',
        'reconciled': 'Reconciled',
      };
      filtered = filtered.filter(inv => inv.status === statusMap[activeTab]);
    }

    if (searchTerm) {
      filtered = filtered.filter(inv =>
        inv.invoice_number?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        inv.business_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        inv.manager_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        inv.event_name?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    return filtered;
  };

  const filteredInvoices = getFilteredInvoices();

  const getStatusCount = (status) => {
    if (status === "all") return visibleInvoices.length;
    return visibleInvoices.filter(inv => inv.status === status).length;
  };

  const getTotalAmount = (status) => {
    const filtered = status === "all"
      ? visibleInvoices
      : visibleInvoices.filter(inv => inv.status === status);
    return filtered.reduce((sum, inv) => sum + (inv.amount || 0), 0);
  };

  const metrics = {
    all: getTotalAmount("all"),
    pending: getTotalAmount("Pending Review"),
    approved: getTotalAmount("Approved"),
    disputed: getTotalAmount("Disputed"),
    overdue: getTotalAmount("Overdue"),
    paid: getTotalAmount("Paid"),
  };

  return (
    <>
      <AutoInvoiceGenerator />
      
      <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
        <div className="max-w-[1600px] mx-auto">
          <PageHeader
            title="Invoices"
            subtitle={`${filteredInvoices.length} invoices • $${metrics.all.toLocaleString()} total`}
            actions={
              userRole === "vendor" && (
                <Button onClick={() => setShowCreateModal(true)} className="bg-[#0A39DF] hover:bg-[#0A39DF]/90">
                  <Plus className="w-5 h-5 mr-2" />
                  Create Invoice
                </Button>
              )
            }
          />

          {/* Alert Banners */}
          {metrics.disputed > 0 && (
            <div className="mb-6 p-4 bg-red-50 border-l-4 border-red-500 rounded-lg flex items-center gap-3">
              <AlertTriangle className="w-5 h-5 text-red-600" />
              <div>
                <p className="font-semibold text-red-900">Disputed Invoices Require Attention</p>
                <p className="text-sm text-red-700">{getStatusCount("Disputed")} invoices are currently disputed</p>
              </div>
            </div>
          )}

          {metrics.overdue > 0 && userRole === "client" && (
            <div className="mb-6 p-4 bg-amber-50 border-l-4 border-amber-500 rounded-lg flex items-center gap-3">
              <Clock className="w-5 h-5 text-amber-600" />
              <div>
                <p className="font-semibold text-amber-900">Overdue Payments</p>
                <p className="text-sm text-amber-700">${metrics.overdue.toLocaleString()} in overdue invoices</p>
              </div>
            </div>
          )}

          {/* Status Tabs */}
          <Tabs value={activeTab} onValueChange={setActiveTab} className="mb-6">
            <TabsList className="bg-white border border-slate-200 h-auto p-1 flex-wrap">
              <TabsTrigger value="all">
                All <Badge variant="secondary" className="ml-2">{getStatusCount("all")}</Badge>
              </TabsTrigger>
              <TabsTrigger value="pending">
                Pending Review <Badge variant="secondary" className="ml-2">{getStatusCount("Pending Review")}</Badge>
              </TabsTrigger>
              <TabsTrigger value="approved">
                Approved <Badge variant="secondary" className="ml-2">{getStatusCount("Approved")}</Badge>
              </TabsTrigger>
              <TabsTrigger value="disputed">
                Disputed <Badge variant="secondary" className="ml-2">{getStatusCount("Disputed")}</Badge>
              </TabsTrigger>
              <TabsTrigger value="overdue">
                Overdue <Badge variant="secondary" className="ml-2">{getStatusCount("Overdue")}</Badge>
              </TabsTrigger>
              <TabsTrigger value="paid">
                Paid <Badge variant="secondary" className="ml-2">{getStatusCount("Paid")}</Badge>
              </TabsTrigger>
              <TabsTrigger value="reconciled">
                Reconciled <Badge variant="secondary" className="ml-2">{getStatusCount("Reconciled")}</Badge>
              </TabsTrigger>
            </TabsList>
          </Tabs>

          {/* Metric Cards */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
            <Card className="border-slate-200">
              <CardContent className="p-4">
                <div className="flex items-center gap-3">
                  <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                    <FileText className="w-6 h-6 text-blue-600" />
                  </div>
                  <div>
                    <p className="text-sm text-slate-500">Total</p>
                    <p className="text-2xl font-bold text-slate-900">${metrics.all.toLocaleString()}</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="border-slate-200">
              <CardContent className="p-4">
                <div className="flex items-center gap-3">
                  <div className="w-12 h-12 bg-amber-100 rounded-lg flex items-center justify-center">
                    <Clock className="w-6 h-6 text-amber-600" />
                  </div>
                  <div>
                    <p className="text-sm text-slate-500">Pending</p>
                    <p className="text-2xl font-bold text-amber-600">${metrics.pending.toLocaleString()}</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="border-slate-200">
              <CardContent className="p-4">
                <div className="flex items-center gap-3">
                  <div className="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                    <AlertTriangle className="w-6 h-6 text-red-600" />
                  </div>
                  <div>
                    <p className="text-sm text-slate-500">Overdue</p>
                    <p className="text-2xl font-bold text-red-600">${metrics.overdue.toLocaleString()}</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="border-slate-200">
              <CardContent className="p-4">
                <div className="flex items-center gap-3">
                  <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                    <CheckCircle className="w-6 h-6 text-green-600" />
                  </div>
                  <div>
                    <p className="text-sm text-slate-500">Paid</p>
                    <p className="text-2xl font-bold text-green-600">${metrics.paid.toLocaleString()}</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Search */}
          <div className="bg-white rounded-lg p-4 mb-6 border border-slate-200">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-slate-400" />
              <Input
                placeholder="Search by invoice number, client, event..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>

          {/* Invoices Table */}
          <Card className="border-slate-200">
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow className="bg-slate-50 hover:bg-slate-50">
                    <TableHead>Invoice #</TableHead>
                    <TableHead>Client</TableHead>
                    <TableHead>Event</TableHead>
                    <TableHead>Vendor</TableHead>
                    <TableHead>Issue Date</TableHead>
                    <TableHead>Due Date</TableHead>
                    <TableHead className="text-right">Amount</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredInvoices.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={9} className="text-center py-12 text-slate-500">
                        <FileText className="w-12 h-12 mx-auto mb-3 text-slate-300" />
                        <p className="font-medium">No invoices found</p>
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredInvoices.map((invoice) => (
                      <TableRow key={invoice.id} className="hover:bg-slate-50">
                        <TableCell className="font-semibold">{invoice.invoice_number}</TableCell>
                        <TableCell>{invoice.business_name}</TableCell>
                        <TableCell>{invoice.event_name}</TableCell>
                        <TableCell>{invoice.vendor_name || "—"}</TableCell>
                        <TableCell>{format(parseISO(invoice.issue_date), 'MMM dd, yyyy')}</TableCell>
                        <TableCell className={isPast(parseISO(invoice.due_date)) && invoice.status !== "Paid" ? "text-red-600 font-semibold" : ""}>
                          {format(parseISO(invoice.due_date), 'MMM dd, yyyy')}
                        </TableCell>
                        <TableCell className="text-right font-bold">${invoice.amount?.toLocaleString()}</TableCell>
                        <TableCell>
                          <Badge className={statusColors[invoice.status]}>
                            {invoice.status}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div className="flex gap-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => navigate(createPageUrl(`InvoiceDetail?id=${invoice.id}`))}
                              className="font-semibold"
                            >
                              <Eye className="w-4 h-4 mr-2" />
                              View
                            </Button>
                            {userRole === "vendor" && invoice.status === "Draft" && (
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => navigate(createPageUrl(`InvoiceEditor?id=${invoice.id}`))}
                                className="font-semibold text-blue-600"
                              >
                                Edit
                              </Button>
                            )}
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </div>
      </div>

      <CreateInvoiceModal
        open={showCreateModal}
        onClose={() => setShowCreateModal(false)}
      />
    </>
  );
}