import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/components/ui/use-toast";
import { base44 } from "@/api/base44Client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Printer, Flag, CheckCircle, MoreVertical, FileText, Edit, CreditCard
} from "lucide-react";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { format, parseISO } from "date-fns";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";

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

export default function InvoiceDetailView({ invoice, userRole, onClose }) {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const [showDisputeDialog, setShowDisputeDialog] = useState(false);
  const [disputeReason, setDisputeReason] = useState("");
  const [disputeDetails, setDisputeDetails] = useState("");
  const [selectedItems, setSelectedItems] = useState([]);

  const updateInvoiceMutation = useMutation({
    mutationFn: ({ id, data }) => base44.entities.Invoice.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['invoices'] });
      toast({
        title: "✅ Invoice Updated",
        description: "Invoice has been updated successfully",
      });
      if (onClose) onClose();
    },
  });

  const handleApprove = async () => {
    const user = await base44.auth.me();
    updateInvoiceMutation.mutate({
      id: invoice.id,
      data: {
        status: "Approved",
        approved_by: user.email,
        approved_date: new Date().toISOString(),
      }
    });
  };

  const handleMarkPaid = async () => {
    const user = await base44.auth.me();
    updateInvoiceMutation.mutate({
      id: invoice.id,
      data: {
        status: "Paid",
        paid_date: new Date().toISOString().split('T')[0],
        payment_method: "Credit Card",
        payment_reference: `PAY-${Date.now()}`,
      }
    });
  };

  const handleEditInvoice = () => {
    navigate(createPageUrl(`InvoiceEditor?id=${invoice.id}`));
  };

  const handleDispute = async () => {
    const user = await base44.auth.me();
    updateInvoiceMutation.mutate({
      id: invoice.id,
      data: {
        status: "Disputed",
        dispute_reason: disputeReason,
        dispute_details: disputeDetails,
        disputed_items: selectedItems,
        disputed_by: user.email,
        disputed_date: new Date().toISOString(),
      }
    });
    setShowDisputeDialog(false);
  };

  const handlePrint = () => {
    window.print();
  };

  const toggleItemSelection = (roleIndex, staffIndex) => {
    const itemId = { role_index: roleIndex, staff_index: staffIndex };
    setSelectedItems(prev => {
      const exists = prev.some(item => item.role_index === roleIndex && item.staff_index === staffIndex);
      if (exists) {
        return prev.filter(item => !(item.role_index === roleIndex && item.staff_index === staffIndex));
      }
      return [...prev, itemId];
    });
  };

  if (!invoice) return null;

  const isClient = userRole === "client";
  const isVendor = userRole === "vendor";
  const isAdmin = userRole === "admin";
  const canEdit = (isVendor || isAdmin) && ["Draft", "Pending Review", "Disputed"].includes(invoice.status);
  const canApprove = isClient && invoice.status === "Pending Review";
  const canPay = isClient && invoice.status === "Approved";
  const canDispute = isClient && ["Pending Review", "Approved"].includes(invoice.status);

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
      <div className="max-w-7xl mx-auto p-6">
        {/* Header */}
        <div className="bg-white rounded-2xl shadow-sm border border-slate-200 p-6 mb-6">
          <div className="flex items-start justify-between mb-4">
            <div className="flex items-center gap-4">
              <FileText className="w-8 h-8 text-[#0A39DF]" />
              <div>
                <h1 className="text-3xl font-bold text-slate-900">{invoice.invoice_number}</h1>
                <Badge className={`${statusColors[invoice.status]} text-white px-3 py-1 mt-2`}>
                  {invoice.status}
                </Badge>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Button variant="outline" onClick={handlePrint}>
                <Printer className="w-4 h-4 mr-2" />
                Print
              </Button>
              {canEdit && (
                <Button variant="outline" className="text-blue-600 border-blue-200 hover:bg-blue-50" onClick={handleEditInvoice}>
                  <Edit className="w-4 h-4 mr-2" />
                  Edit Invoice
                </Button>
              )}
              {canDispute && (
                <Button variant="outline" className="text-red-600 border-red-200 hover:bg-red-50" onClick={() => setShowDisputeDialog(true)}>
                  <Flag className="w-4 h-4 mr-2" />
                  Dispute Invoice
                </Button>
              )}
              {canApprove && (
                <Button className="bg-green-600 hover:bg-green-700" onClick={handleApprove}>
                  <CheckCircle className="w-4 h-4 mr-2" />
                  Approve Invoice
                </Button>
              )}
              {canPay && (
                <Button className="bg-[#0A39DF] hover:bg-[#0831b8]" onClick={handleMarkPaid}>
                  <CreditCard className="w-4 h-4 mr-2" />
                  Mark as Paid
                </Button>
              )}
            </div>
          </div>

          {/* Event Info */}
          <div className="flex flex-wrap gap-6 text-sm text-slate-600">
            <div>
              <span className="font-semibold">Event Name:</span> {invoice.event_name}
            </div>
            <div>
              <span className="font-semibold">PO#:</span> {invoice.po_reference || "N/A"}
            </div>
            <div>
              <span className="font-semibold">Date:</span> {invoice.event_date ? format(parseISO(invoice.event_date), 'M.d.yyyy') : '—'}
            </div>
            <div>
              <span className="font-semibold">Due date:</span> <span className="text-red-600 font-bold">{format(parseISO(invoice.due_date), 'M.d.yyyy')}</span>
            </div>
          </div>
        </div>

        {/* KROW Logo */}
        <div className="mb-6">
          <img 
            src="https://qtrypzzcjebvfcihiynt.supabase.co/storage/v1/object/public/base44-prod/public/68fc6cf01386035c266e7a5d/3ba390829_KROWlogo.png" 
            alt="KROW" 
            className="h-12"
          />
        </div>

        {/* From and To */}
        <div className="grid grid-cols-2 gap-6 mb-8">
          <div className="bg-blue-50 rounded-xl p-6 border-2 border-blue-200">
            <div className="flex items-center gap-2 mb-4">
              <div className="w-8 h-8 bg-[#0A39DF] rounded-full flex items-center justify-center">
                <span className="text-white font-bold text-sm">F</span>
              </div>
              <h3 className="font-bold text-lg text-slate-900">From:</h3>
            </div>
            <div className="space-y-2">
              <p className="font-bold text-lg text-slate-900">{invoice.from_company?.name || invoice.vendor_name || "Vendor Name"}</p>
              {(invoice.from_company?.address || invoice.vendor_address) && (
                <div className="text-sm text-slate-700">
                  <p className="font-semibold text-slate-500 text-xs mb-1">Address</p>
                  <p>{invoice.from_company?.address || invoice.vendor_address}</p>
                </div>
              )}
              {(invoice.from_company?.email || invoice.vendor_email) && (
                <div className="text-sm text-slate-700">
                  <p className="font-semibold text-slate-500 text-xs mb-1">Email</p>
                  <p>{invoice.from_company?.email || invoice.vendor_email}</p>
                </div>
              )}
              {(invoice.from_company?.phone || invoice.vendor_phone) && (
                <div className="text-sm text-slate-700">
                  <p className="font-semibold text-slate-500 text-xs mb-1">Phone</p>
                  <p>{invoice.from_company?.phone || invoice.vendor_phone}</p>
                </div>
              )}
              {(invoice.from_company?.contact || invoice.vendor_contact) && (
                <div className="text-sm text-slate-700">
                  <p className="font-semibold text-slate-500 text-xs mb-1">Point of Contact</p>
                  <p>{invoice.from_company?.contact || invoice.vendor_contact}</p>
                </div>
              )}
            </div>
          </div>

          <div className="bg-green-50 rounded-xl p-6 border-2 border-green-200">
            <div className="flex items-center gap-2 mb-4">
              <div className="w-8 h-8 bg-green-600 rounded-full flex items-center justify-center">
                <span className="text-white font-bold text-sm">T</span>
              </div>
              <h3 className="font-bold text-lg text-slate-900">To:</h3>
            </div>
            <div className="space-y-1 text-sm">
              <p className="font-bold text-slate-900">{invoice.to_company?.name || invoice.business_name}</p>
              <p className="text-slate-600">{invoice.to_company?.address}</p>
              <p className="text-slate-600">{invoice.to_company?.email}</p>
              <div className="grid grid-cols-2 gap-4 mt-3 pt-3 border-t border-green-200">
                <div>
                  <p className="text-xs text-slate-500">Main Kitchen</p>
                  <p className="font-semibold text-slate-900">{invoice.to_company?.manager || invoice.manager_name}</p>
                </div>
                <div>
                  <p className="text-xs text-slate-500">Manager Name</p>
                  <p className="font-semibold text-slate-900">{invoice.to_company?.phone}</p>
                </div>
              </div>
              <p className="text-slate-600">{invoice.to_company?.vendor_id || "Vendor #"}</p>
            </div>
          </div>
        </div>

        {/* Staff Charges Table */}
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden mb-6">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-slate-50 border-b border-slate-200">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-bold text-slate-700">#</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-slate-700">Date</th>
                  <th className="px-4 py-3 text-left text-xs font-bold text-slate-700">Position</th>
                  <th className="px-4 py-3 text-right text-xs font-bold text-slate-700">Worked Hours</th>
                  <th className="px-4 py-3 text-right text-xs font-bold text-slate-700">Reg Hours</th>
                  <th className="px-4 py-3 text-right text-xs font-bold text-slate-700">OT Hours</th>
                  <th className="px-4 py-3 text-right text-xs font-bold text-slate-700">DT Hours</th>
                  <th className="px-4 py-3 text-right text-xs font-bold text-slate-700">Reg Value</th>
                  <th className="px-4 py-3 text-right text-xs font-bold text-slate-700">OT Value</th>
                  <th className="px-4 py-3 text-right text-xs font-bold text-slate-700">DT Value</th>
                  <th className="px-4 py-3 text-right text-xs font-bold text-slate-700">Total</th>
                  <th className="px-4 py-3 text-center text-xs font-bold text-slate-700">Actions</th>
                </tr>
              </thead>
              <tbody>
                {invoice.roles?.map((roleGroup, roleIdx) => (
                  <React.Fragment key={roleIdx}>
                    {roleGroup.staff_entries?.map((entry, entryIdx) => (
                      <tr key={`${roleIdx}-${entryIdx}`} className="border-b border-slate-100 hover:bg-slate-50">
                        <td className="px-4 py-3 text-sm text-slate-900">{roleIdx + 1}</td>
                        <td className="px-4 py-3 text-sm text-slate-600">{entry.date ? format(parseISO(entry.date), 'M/d/yyyy') : '—'}</td>
                        <td className="px-4 py-3 text-sm font-medium text-slate-900">{entry.position}</td>
                        <td className="px-4 py-3 text-sm text-right text-slate-700">{entry.worked_hours?.toFixed(2) || '0.00'}</td>
                        <td className="px-4 py-3 text-sm text-right text-slate-700">{entry.regular_hours?.toFixed(2) || '0.00'}</td>
                        <td className="px-4 py-3 text-sm text-right text-slate-700">{entry.ot_hours?.toFixed(2) || '0.00'}</td>
                        <td className="px-4 py-3 text-sm text-right text-slate-700">{entry.dt_hours?.toFixed(2) || '0.00'}</td>
                        <td className="px-4 py-3 text-sm text-right text-slate-700">${entry.regular_value?.toFixed(2) || '0.00'}</td>
                        <td className="px-4 py-3 text-sm text-right text-slate-700">${entry.ot_value?.toFixed(2) || '0.00'}</td>
                        <td className="px-4 py-3 text-sm text-right text-slate-700">${entry.dt_value?.toFixed(2) || '0.00'}</td>
                        <td className="px-4 py-3 text-sm text-right font-bold text-slate-900">${entry.total?.toFixed(2) || '0.00'}</td>
                        <td className="px-4 py-3 text-center">
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon" className="h-8 w-8">
                                <MoreVertical className="w-4 h-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem>View Details</DropdownMenuItem>
                              <DropdownMenuItem className="text-red-600">Flag Entry</DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </td>
                      </tr>
                    ))}
                    <tr className="bg-slate-100 font-semibold">
                      <td colSpan="10" className="px-4 py-2 text-sm text-slate-700">Total</td>
                      <td className="px-4 py-2 text-sm text-right font-bold">${roleGroup.role_subtotal?.toFixed(2)}</td>
                      <td></td>
                    </tr>
                  </React.Fragment>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* Other Charges */}
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden mb-6">
          <div className="bg-slate-50 px-6 py-3 border-b border-slate-200">
            <h3 className="font-bold text-slate-900">Other charges</h3>
          </div>
          <table className="w-full">
            <thead className="bg-slate-50 border-b border-slate-200">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-bold text-slate-700">#</th>
                <th className="px-6 py-3 text-left text-xs font-bold text-slate-700">Charge</th>
                <th className="px-6 py-3 text-right text-xs font-bold text-slate-700">QTY</th>
                <th className="px-6 py-3 text-right text-xs font-bold text-slate-700">Rate</th>
                <th className="px-6 py-3 text-right text-xs font-bold text-slate-700">Amount</th>
              </tr>
            </thead>
            <tbody>
              {(!invoice.other_charges || invoice.other_charges === 0) ? (
                <tr>
                  <td colSpan="5" className="px-6 py-8 text-center text-sm text-slate-500">
                    No additional charges
                  </td>
                </tr>
              ) : (
                <tr className="border-b border-slate-100">
                  <td className="px-6 py-3 text-sm">1</td>
                  <td className="px-6 py-3 text-sm">Additional Charges</td>
                  <td className="px-6 py-3 text-sm text-right">1</td>
                  <td className="px-6 py-3 text-sm text-right">${invoice.other_charges?.toFixed(2)}</td>
                  <td className="px-6 py-3 text-sm text-right font-semibold">${invoice.other_charges?.toFixed(2)}</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Totals */}
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
          <div className="max-w-md ml-auto space-y-3">
            <div className="flex justify-between text-base">
              <span className="text-slate-600">Sub-total:</span>
              <span className="font-bold text-slate-900">${invoice.subtotal?.toFixed(2)}</span>
            </div>
            <div className="flex justify-between text-base">
              <span className="text-slate-600">Other charges:</span>
              <span className="font-bold text-slate-900">${(invoice.other_charges || 0)?.toFixed(2)}</span>
            </div>
            <div className="border-t-2 border-slate-300 pt-3 flex justify-between text-xl">
              <span className="font-bold text-slate-900">Grand total:</span>
              <span className="font-bold text-[#0A39DF]">${invoice.amount?.toFixed(2)}</span>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="mt-8 flex items-center justify-between text-sm text-slate-500">
          <img 
            src="https://qtrypzzcjebvfcihiynt.supabase.co/storage/v1/object/public/base44-prod/public/68fc6cf01386035c266e7a5d/3ba390829_KROWlogo.png" 
            alt="KROW" 
            className="h-8"
          />
          <span>Page 1</span>
        </div>
      </div>

      {/* Dispute Dialog */}
      <Dialog open={showDisputeDialog} onOpenChange={setShowDisputeDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Dispute Invoice</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div>
              <Label>Reason for Dispute</Label>
              <Select value={disputeReason} onValueChange={setDisputeReason}>
                <SelectTrigger>
                  <SelectValue placeholder="Select reason" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Incorrect Hours">Incorrect Hours</SelectItem>
                  <SelectItem value="Incorrect Rate">Incorrect Rate</SelectItem>
                  <SelectItem value="Unauthorized Staff">Unauthorized Staff</SelectItem>
                  <SelectItem value="Service Not Rendered">Service Not Rendered</SelectItem>
                  <SelectItem value="Calculation Error">Calculation Error</SelectItem>
                  <SelectItem value="Other">Other</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>Details</Label>
              <Textarea
                value={disputeDetails}
                onChange={(e) => setDisputeDetails(e.target.value)}
                placeholder="Provide detailed information about the dispute..."
                rows={5}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDisputeDialog(false)}>
              Cancel
            </Button>
            <Button 
              onClick={handleDispute}
              disabled={!disputeReason}
              className="bg-red-600 hover:bg-red-700"
            >
              Submit Dispute
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}