import React, { useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
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 { Separator } from "@/components/ui/separator";
import { useToast } from "@/components/ui/use-toast";
import { base44 } from "@/api/base44Client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
  FileText, Download, Mail, Printer, CheckCircle,
  XCircle, AlertTriangle, DollarSign, Calendar, Building2,
  User, CreditCard, Edit3, Flag, CheckCheck
} from "lucide-react";
import { format, parseISO } from "date-fns";

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 InvoiceDetailModal({ open, onClose, invoice, userRole }) {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [disputeMode, setDisputeMode] = useState(false);
  const [disputeReason, setDisputeReason] = useState("");
  const [disputeDetails, setDisputeDetails] = useState("");
  const [paymentMethod, setPaymentMethod] = useState("");
  const [paymentRef, setPaymentRef] = 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",
      });
      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 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(),
      }
    });
  };

  const handlePay = async () => {
    updateInvoiceMutation.mutate({
      id: invoice.id,
      data: {
        status: "Paid",
        paid_date: new Date().toISOString().split('T')[0],
        payment_method: paymentMethod,
        payment_reference: paymentRef,
      }
    });
  };

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

  const handleEmailInvoice = async () => {
    const user = await base44.auth.me();
    await base44.integrations.Core.SendEmail({
      to: invoice.business_name || user.email,
      subject: `Invoice ${invoice.invoice_number}`,
      body: `Please find attached invoice ${invoice.invoice_number} for ${invoice.event_name}. Amount: $${invoice.amount}. Due: ${invoice.due_date}`,
    });
    toast({
      title: "✅ Email Sent",
      description: "Invoice has been emailed successfully",
    });
  };

  const toggleItemSelection = (index) => {
    setSelectedItems(prev =>
      prev.includes(index) ? prev.filter(i => i !== index) : [...prev, index]
    );
  };

  if (!invoice) return null;

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

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <div className="flex items-start justify-between">
            <div>
              <DialogTitle className="text-2xl font-bold">{invoice.invoice_number}</DialogTitle>
              <p className="text-sm text-slate-500 mt-1">{invoice.event_name}</p>
            </div>
            <Badge className={`${statusColors[invoice.status]} text-white px-4 py-2`}>
              {invoice.status}
            </Badge>
          </div>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* Header Information */}
          <div className="grid grid-cols-2 gap-6">
            {/* From Section */}
            <div className="bg-blue-50 rounded-lg p-4">
              <div className="flex items-center gap-2 mb-3">
                <div className="w-8 h-8 bg-[#0A39DF] rounded-full flex items-center justify-center">
                  <Building2 className="w-4 h-4 text-white" />
                </div>
                <h3 className="font-bold text-slate-900">From:</h3>
              </div>
              <div className="space-y-1 text-sm">
                <p className="font-semibold">{invoice.from_company?.name || invoice.vendor_name}</p>
                <p className="text-slate-600">{invoice.from_company?.address}</p>
                <p className="text-slate-600">{invoice.from_company?.email}</p>
                <p className="text-slate-600">{invoice.from_company?.phone}</p>
              </div>
            </div>

            {/* To Section */}
            <div className="bg-green-50 rounded-lg p-4">
              <div className="flex items-center gap-2 mb-3">
                <div className="w-8 h-8 bg-green-600 rounded-full flex items-center justify-center">
                  <User className="w-4 h-4 text-white" />
                </div>
                <h3 className="font-bold text-slate-900">To:</h3>
              </div>
              <div className="space-y-1 text-sm">
                <p className="font-semibold">{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>
                <p className="font-semibold text-slate-900 mt-2">{invoice.to_company?.manager || invoice.manager_name}</p>
                <p className="text-slate-600">{invoice.to_company?.phone}</p>
                <p className="text-slate-600">{invoice.to_company?.vendor_id}</p>
              </div>
            </div>
          </div>

          {/* Event Details */}
          <div className="bg-slate-50 rounded-lg p-4">
            <div className="grid grid-cols-3 gap-4 text-sm">
              <div>
                <span className="text-slate-500">Event Date:</span>
                <span className="ml-2 font-semibold">{invoice.event_date ? format(parseISO(invoice.event_date), 'MMM dd, yyyy') : '—'}</span>
              </div>
              <div>
                <span className="text-slate-500">PO #:</span>
                <span className="ml-2 font-semibold">{invoice.po_reference || '—'}</span>
              </div>
              <div>
                <span className="text-slate-500">Due Date:</span>
                <span className="ml-2 font-semibold text-red-600">{format(parseISO(invoice.due_date), 'MMM dd, yyyy')}</span>
              </div>
            </div>
          </div>

          <Separator />

          {/* Roles and Staff Charges */}
          <div className="space-y-6">
            <h3 className="font-semibold text-lg">Staff Charges</h3>
            
            {invoice.roles?.map((roleGroup, roleIdx) => (
              <div key={roleIdx} className="border border-slate-200 rounded-lg overflow-hidden">
                <div className="bg-slate-100 px-4 py-2 border-b border-slate-200">
                  <h4 className="font-bold text-slate-900">Role: {roleGroup.role_name}</h4>
                </div>
                <div className="overflow-x-auto">
                  <table className="w-full text-xs">
                    <thead className="bg-slate-50">
                      <tr>
                        {disputeMode && <th className="p-2 text-left font-semibold">Flag</th>}
                        <th className="p-2 text-left font-semibold">Name</th>
                        <th className="p-2 text-left font-semibold">Check-In</th>
                        <th className="p-2 text-left font-semibold">Check-Out</th>
                        <th className="p-2 text-right font-semibold">Worked</th>
                        <th className="p-2 text-right font-semibold">Reg Hrs</th>
                        <th className="p-2 text-right font-semibold">OT Hrs</th>
                        <th className="p-2 text-right font-semibold">DT Hrs</th>
                        <th className="p-2 text-right font-semibold">Rate</th>
                        <th className="p-2 text-right font-semibold">Reg Value</th>
                        <th className="p-2 text-right font-semibold">OT Value</th>
                        <th className="p-2 text-right font-semibold">DT Value</th>
                        <th className="p-2 text-right font-semibold">Total</th>
                      </tr>
                    </thead>
                    <tbody>
                      {roleGroup.staff_entries?.map((entry, entryIdx) => (
                        <tr key={entryIdx} className={`border-t border-slate-200 ${selectedItems.some(item => item.role_index === roleIdx && item.staff_index === entryIdx) ? 'bg-red-50' : ''}`}>
                          {disputeMode && (
                            <td className="p-2">
                              <input
                                type="checkbox"
                                checked={selectedItems.some(item => item.role_index === roleIdx && item.staff_index === entryIdx)}
                                onChange={() => {
                                  const itemId = { role_index: roleIdx, staff_index: entryIdx };
                                  setSelectedItems(prev =>
                                    prev.some(item => item.role_index === roleIdx && item.staff_index === entryIdx)
                                      ? prev.filter(item => !(item.role_index === roleIdx && item.staff_index === entryIdx))
                                      : [...prev, itemId]
                                  );
                                }}
                                className="w-4 h-4"
                              />
                            </td>
                          )}
                          <td className="p-2">{entry.staff_name}</td>
                          <td className="p-2">{entry.check_in}</td>
                          <td className="p-2">{entry.check_out}</td>
                          <td className="p-2 text-right">{entry.worked_hours?.toFixed(2)}</td>
                          <td className="p-2 text-right">{entry.regular_hours?.toFixed(2)}</td>
                          <td className="p-2 text-right">{entry.ot_hours?.toFixed(2)}</td>
                          <td className="p-2 text-right">{entry.dt_hours?.toFixed(2)}</td>
                          <td className="p-2 text-right">${entry.rate?.toFixed(2)}</td>
                          <td className="p-2 text-right">${entry.regular_value?.toFixed(2)}</td>
                          <td className="p-2 text-right">${entry.ot_value?.toFixed(2)}</td>
                          <td className="p-2 text-right">${entry.dt_value?.toFixed(2)}</td>
                          <td className="p-2 text-right font-bold">${entry.total?.toFixed(2)}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <div className="bg-slate-50 px-4 py-2 border-t border-slate-200 flex justify-end">
                  <span className="font-bold">Role Total: ${roleGroup.role_subtotal?.toFixed(2)}</span>
                </div>
              </div>
            ))}
          </div>

          {/* Totals */}
          <div className="bg-slate-50 rounded-lg p-4">
            <div className="space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-slate-600">Sub-total:</span>
                <span className="font-semibold">${invoice.subtotal?.toFixed(2)}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-slate-600">Other charges:</span>
                <span className="font-semibold">${(invoice.other_charges || 0)?.toFixed(2)}</span>
              </div>
              <Separator />
              <div className="flex justify-between text-lg">
                <span className="font-bold">Grand total:</span>
                <span className="font-bold text-[#0A39DF]">${invoice.amount?.toFixed(2)}</span>
              </div>
            </div>
          </div>

          {/* Dispute Section */}
          {disputeMode && (
            <div className="bg-red-50 border border-red-200 rounded-lg p-4 space-y-3">
              <div className="flex items-center gap-2">
                <AlertTriangle className="w-5 h-5 text-red-600" />
                <h3 className="font-semibold text-red-900">Dispute Invoice</h3>
              </div>
              <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="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={4}
                />
              </div>
            </div>
          )}

          {/* Payment Section */}
          {invoice.status === "Approved" && isClient && (
            <div className="bg-green-50 border border-green-200 rounded-lg p-4 space-y-3">
              <div className="flex items-center gap-2">
                <CreditCard className="w-5 h-5 text-green-600" />
                <h3 className="font-semibold text-green-900">Record Payment</h3>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <Label>Payment Method</Label>
                  <Select value={paymentMethod} onValueChange={setPaymentMethod}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select method" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="Credit Card">Credit Card</SelectItem>
                      <SelectItem value="ACH">ACH Transfer</SelectItem>
                      <SelectItem value="Wire Transfer">Wire Transfer</SelectItem>
                      <SelectItem value="Check">Check</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>Reference Number</Label>
                  <input
                    type="text"
                    value={paymentRef}
                    onChange={(e) => setPaymentRef(e.target.value)}
                    placeholder="Transaction ID"
                    className="w-full px-3 py-2 border border-slate-300 rounded-md"
                  />
                </div>
              </div>
            </div>
          )}

          {/* Dispute Info */}
          {invoice.status === "Disputed" && (
            <div className="bg-amber-50 border border-amber-200 rounded-lg p-4">
              <h3 className="font-semibold text-amber-900 mb-2">Dispute Information</h3>
              <p className="text-sm text-slate-700"><strong>Reason:</strong> {invoice.dispute_reason}</p>
              <p className="text-sm text-slate-700 mt-1"><strong>Details:</strong> {invoice.dispute_details}</p>
              <p className="text-xs text-slate-500 mt-2">Disputed by {invoice.disputed_by} on {format(parseISO(invoice.disputed_date), 'MMM dd, yyyy')}</p>
            </div>
          )}

          {/* Notes */}
          {invoice.notes && (
            <div>
              <Label className="text-sm font-semibold">Notes</Label>
              <p className="text-sm text-slate-600 mt-1">{invoice.notes}</p>
            </div>
          )}
        </div>

        <DialogFooter className="flex flex-wrap gap-2">
          <div className="flex gap-2 flex-wrap w-full justify-between">
            <div className="flex gap-2">
              <Button variant="outline" onClick={handleDownloadPDF}>
                <Download className="w-4 h-4 mr-2" />
                Download
              </Button>
              <Button variant="outline" onClick={handleEmailInvoice}>
                <Mail className="w-4 h-4 mr-2" />
                Email
              </Button>
              <Button variant="outline" onClick={() => window.print()}>
                <Printer className="w-4 h-4 mr-2" />
                Print
              </Button>
            </div>

            <div className="flex gap-2">
              {canApprove && (
                <Button onClick={handleApprove} className="bg-green-600 hover:bg-green-700">
                  <CheckCheck className="w-4 h-4 mr-2" />
                  Approve
                </Button>
              )}

              {canDispute && !disputeMode && (
                <Button onClick={() => setDisputeMode(true)} variant="destructive">
                  <Flag className="w-4 h-4 mr-2" />
                  Dispute
                </Button>
              )}

              {disputeMode && (
                <>
                  <Button variant="outline" onClick={() => setDisputeMode(false)}>
                    Cancel
                  </Button>
                  <Button onClick={handleDispute} variant="destructive" disabled={!disputeReason}>
                    Submit Dispute
                  </Button>
                </>
              )}

              {canPay && (
                <Button
                  onClick={handlePay}
                  disabled={!paymentMethod}
                  className="bg-[#0A39DF] hover:bg-[#0A39DF]/90"
                >
                  <DollarSign className="w-4 h-4 mr-2" />
                  Mark as Paid
                </Button>
              )}

              {canEdit && (
                <Button variant="outline">
                  <Edit3 className="w-4 h-4 mr-2" />
                  Edit
                </Button>
              )}
            </div>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}