import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Calendar, Copy, FileText, Search, Clock, Users, MapPin, Zap, Save, Star, Trash2 } from "lucide-react";
import { format, parseISO } from "date-fns";

export default function InvoiceQuickActions({ 
  events = [], 
  invoices = [], 
  templates = [],
  onImportFromEvent, 
  onDuplicateInvoice,
  onUseTemplate,
  onSaveTemplate,
  onDeleteTemplate
}) {
  const [eventDialogOpen, setEventDialogOpen] = useState(false);
  const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false);
  const [templateDialogOpen, setTemplateDialogOpen] = useState(false);
  const [saveTemplateDialogOpen, setSaveTemplateDialogOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [templateName, setTemplateName] = useState("");

  // Filter completed events that can be invoiced
  const completedEvents = events.filter(e => 
    e.status === "Completed" || e.status === "Active" || e.status === "Confirmed"
  );

  // Filter events by search
  const filteredEvents = completedEvents.filter(e =>
    e.event_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    e.business_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    e.hub?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // Filter invoices for duplication
  const filteredInvoices = invoices.filter(inv =>
    inv.invoice_number?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    inv.business_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    inv.event_name?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // Filter templates
  const filteredTemplates = templates.filter(t =>
    t.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    t.client_name?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const handleImportEvent = (event) => {
    onImportFromEvent(event);
    setEventDialogOpen(false);
    setSearchTerm("");
  };

  const handleDuplicate = (invoice) => {
    onDuplicateInvoice(invoice);
    setDuplicateDialogOpen(false);
    setSearchTerm("");
  };

  const handleUseTemplate = (template) => {
    onUseTemplate(template);
    setTemplateDialogOpen(false);
    setSearchTerm("");
  };

  const handleSaveTemplate = () => {
    if (templateName.trim()) {
      onSaveTemplate(templateName.trim());
      setSaveTemplateDialogOpen(false);
      setTemplateName("");
    }
  };

  return (
    <div className="mb-6 p-4 bg-gradient-to-r from-amber-50 to-orange-100 rounded-xl border-2 border-amber-200">
      <div className="flex items-center gap-3 mb-3">
        <div className="w-10 h-10 bg-amber-500 rounded-lg flex items-center justify-center">
          <Zap className="w-5 h-5 text-white" />
        </div>
        <div>
          <h3 className="font-bold text-amber-900">Quick Actions</h3>
          <p className="text-xs text-amber-700">Save time with these shortcuts</p>
        </div>
      </div>

      <div className="flex flex-wrap gap-2">
        {/* Import from Event */}
        <Dialog open={eventDialogOpen} onOpenChange={setEventDialogOpen}>
          <DialogTrigger asChild>
            <Button variant="outline" size="sm" className="bg-white border-amber-300 hover:bg-amber-50 text-amber-800">
              <Calendar className="w-4 h-4 mr-2" />
              Import from Event
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[80vh] overflow-hidden flex flex-col">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <Calendar className="w-5 h-5 text-blue-600" />
                Import Staff Data from Event
              </DialogTitle>
            </DialogHeader>
            <div className="relative mb-4">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
              <Input
                placeholder="Search events by name, client, or hub..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-9"
              />
            </div>
            <div className="overflow-y-auto flex-1 space-y-2 pr-2">
              {filteredEvents.length === 0 ? (
                <div className="text-center py-8 text-slate-500">
                  <Calendar className="w-12 h-12 mx-auto mb-2 text-slate-300" />
                  <p>No completed events found</p>
                </div>
              ) : (
                filteredEvents.map(event => (
                  <button
                    key={event.id}
                    onClick={() => handleImportEvent(event)}
                    className="w-full p-4 bg-white border border-slate-200 rounded-lg hover:border-blue-400 hover:bg-blue-50 transition-all text-left"
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <h4 className="font-semibold text-slate-900">{event.event_name}</h4>
                        <div className="flex items-center gap-3 mt-1 text-sm text-slate-600">
                          <span className="flex items-center gap-1">
                            <Users className="w-3 h-3" />
                            {event.assigned_staff?.length || 0} staff
                          </span>
                          <span className="flex items-center gap-1">
                            <MapPin className="w-3 h-3" />
                            {event.hub || event.event_location || "—"}
                          </span>
                          <span className="flex items-center gap-1">
                            <Clock className="w-3 h-3" />
                            {event.date ? format(parseISO(event.date), 'MMM d, yyyy') : "—"}
                          </span>
                        </div>
                        <p className="text-xs text-slate-500 mt-1">{event.business_name}</p>
                      </div>
                      <Badge className={`${event.status === 'Completed' ? 'bg-emerald-100 text-emerald-700' : 'bg-blue-100 text-blue-700'}`}>
                        {event.status}
                      </Badge>
                    </div>
                  </button>
                ))
              )}
            </div>
          </DialogContent>
        </Dialog>

        {/* Duplicate Invoice */}
        <Dialog open={duplicateDialogOpen} onOpenChange={setDuplicateDialogOpen}>
          <DialogTrigger asChild>
            <Button variant="outline" size="sm" className="bg-white border-amber-300 hover:bg-amber-50 text-amber-800">
              <Copy className="w-4 h-4 mr-2" />
              Duplicate Invoice
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[80vh] overflow-hidden flex flex-col">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <Copy className="w-5 h-5 text-purple-600" />
                Duplicate an Existing Invoice
              </DialogTitle>
            </DialogHeader>
            <div className="relative mb-4">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
              <Input
                placeholder="Search by invoice #, client, or event..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-9"
              />
            </div>
            <div className="overflow-y-auto flex-1 space-y-2 pr-2">
              {filteredInvoices.length === 0 ? (
                <div className="text-center py-8 text-slate-500">
                  <FileText className="w-12 h-12 mx-auto mb-2 text-slate-300" />
                  <p>No invoices found</p>
                </div>
              ) : (
                filteredInvoices.slice(0, 20).map(invoice => (
                  <button
                    key={invoice.id}
                    onClick={() => handleDuplicate(invoice)}
                    className="w-full p-4 bg-white border border-slate-200 rounded-lg hover:border-purple-400 hover:bg-purple-50 transition-all text-left"
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <h4 className="font-bold text-slate-900">{invoice.invoice_number}</h4>
                          <Badge variant="outline" className="text-xs">${invoice.amount?.toLocaleString() || 0}</Badge>
                        </div>
                        <p className="text-sm text-slate-700 mt-1">{invoice.business_name}</p>
                        <div className="flex items-center gap-3 mt-1 text-xs text-slate-500">
                          <span>{invoice.event_name || "No event"}</span>
                          <span>•</span>
                          <span>{invoice.roles?.[0]?.staff_entries?.length || 0} staff entries</span>
                          <span>•</span>
                          <span>{invoice.issue_date ? format(parseISO(invoice.issue_date), 'MMM d, yyyy') : "—"}</span>
                        </div>
                      </div>
                      <Badge className={`${invoice.status === 'Paid' ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-600'}`}>
                        {invoice.status}
                      </Badge>
                    </div>
                  </button>
                ))
              )}
            </div>
          </DialogContent>
        </Dialog>

        {/* Use Template */}
        <Dialog open={templateDialogOpen} onOpenChange={setTemplateDialogOpen}>
          <DialogTrigger asChild>
            <Button variant="outline" size="sm" className="bg-white border-amber-300 hover:bg-amber-50 text-amber-800">
              <FileText className="w-4 h-4 mr-2" />
              Use Template
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[80vh] overflow-hidden flex flex-col">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <FileText className="w-5 h-5 text-emerald-600" />
                Invoice Templates
              </DialogTitle>
            </DialogHeader>
            <div className="relative mb-4">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
              <Input
                placeholder="Search templates..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-9"
              />
            </div>
            <div className="overflow-y-auto flex-1 space-y-2 pr-2">
              {filteredTemplates.length === 0 ? (
                <div className="text-center py-8 text-slate-500">
                  <Star className="w-12 h-12 mx-auto mb-2 text-slate-300" />
                  <p>No templates saved yet</p>
                  <p className="text-xs mt-1">Create an invoice and save it as a template</p>
                </div>
              ) : (
                filteredTemplates.map(template => (
                  <div
                    key={template.id}
                    className="w-full p-4 bg-white border border-slate-200 rounded-lg hover:border-emerald-400 hover:bg-emerald-50 transition-all"
                  >
                    <div className="flex items-start justify-between">
                      <button
                        onClick={() => handleUseTemplate(template)}
                        className="flex-1 text-left"
                      >
                        <div className="flex items-center gap-2">
                          <Star className="w-4 h-4 text-amber-500 fill-amber-500" />
                          <h4 className="font-semibold text-slate-900">{template.name}</h4>
                        </div>
                        <p className="text-sm text-slate-600 mt-1">{template.client_name}</p>
                        <div className="flex items-center gap-3 mt-1 text-xs text-slate-500">
                          <span>{template.staff_count || 0} staff entries</span>
                          <span>•</span>
                          <span>{template.charges_count || 0} charges</span>
                        </div>
                      </button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => onDeleteTemplate(template.id)}
                        className="text-red-500 hover:text-red-700 hover:bg-red-50"
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                ))
              )}
            </div>
          </DialogContent>
        </Dialog>

        {/* Save as Template */}
        <Dialog open={saveTemplateDialogOpen} onOpenChange={setSaveTemplateDialogOpen}>
          <DialogTrigger asChild>
            <Button variant="outline" size="sm" className="bg-white border-amber-300 hover:bg-amber-50 text-amber-800">
              <Save className="w-4 h-4 mr-2" />
              Save as Template
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <Save className="w-5 h-5 text-blue-600" />
                Save Current Invoice as Template
              </DialogTitle>
            </DialogHeader>
            <div className="space-y-4 py-4">
              <div>
                <label className="text-sm font-medium text-slate-700">Template Name</label>
                <Input
                  placeholder="e.g., Google Weekly Catering, Standard Event Setup..."
                  value={templateName}
                  onChange={(e) => setTemplateName(e.target.value)}
                  className="mt-1"
                />
                <p className="text-xs text-slate-500 mt-1">
                  This will save client info, positions, rates, and charges as a reusable template
                </p>
              </div>
              <div className="flex justify-end gap-2">
                <Button variant="outline" onClick={() => setSaveTemplateDialogOpen(false)}>
                  Cancel
                </Button>
                <Button 
                  onClick={handleSaveTemplate}
                  disabled={!templateName.trim()}
                  className="bg-blue-600 hover:bg-blue-700"
                >
                  <Save className="w-4 h-4 mr-2" />
                  Save Template
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>
    </div>
  );
}