import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Download, FileText, FileSpreadsheet, Code, Send, Check, Loader2, Building2, Link2 } from "lucide-react";

const ERP_SYSTEMS = {
  "SAP Ariba": { format: "cXML", color: "bg-blue-100 text-blue-700" },
  "Fieldglass": { format: "CSV", color: "bg-purple-100 text-purple-700" },
  "CrunchTime": { format: "JSON", color: "bg-orange-100 text-orange-700" },
  "Coupa": { format: "cXML", color: "bg-teal-100 text-teal-700" },
  "Oracle NetSuite": { format: "CSV", color: "bg-red-100 text-red-700" },
  "Workday": { format: "JSON", color: "bg-green-100 text-green-700" },
};

export default function InvoiceExportPanel({ invoice, business, onExport }) {
  const [exportFormat, setExportFormat] = useState(business?.edi_format || "CSV");
  const [isExporting, setIsExporting] = useState(false);
  const [exportSuccess, setExportSuccess] = useState(false);

  const erpSystem = business?.erp_system || "None";
  const erpInfo = ERP_SYSTEMS[erpSystem];

  const generateEDI810 = () => {
    // EDI 810 Invoice format
    const segments = [
      `ISA*00*          *00*          *ZZ*KROW           *ZZ*${business?.erp_vendor_id || 'CLIENT'}       *${new Date().toISOString().slice(2,10).replace(/-/g,'')}*${new Date().toTimeString().slice(0,5).replace(':','')}*U*00401*000000001*0*P*>~`,
      `GS*IN*KROW*${business?.business_name?.substring(0,15) || 'CLIENT'}*${new Date().toISOString().slice(0,10).replace(/-/g,'')}*${new Date().toTimeString().slice(0,4).replace(':','')}*1*X*004010~`,
      `ST*810*0001~`,
      `BIG*${invoice.issue_date?.replace(/-/g,'')}*${invoice.invoice_number}*${invoice.event_date?.replace(/-/g,'')}*${invoice.po_reference || ''}~`,
      `N1*BT*${business?.business_name || invoice.business_name}~`,
      `N1*ST*${invoice.hub || business?.hub_building || ''}~`,
      `ITD*01*3*****${invoice.due_date?.replace(/-/g,'')}~`,
      `TDS*${Math.round((invoice.amount || 0) * 100)}~`,
      `SE*8*0001~`,
      `GE*1*1~`,
      `IEA*1*000000001~`
    ];
    return segments.join('\n');
  };

  const generateCXML = () => {
    return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.014/InvoiceDetail.dtd">
<cXML payloadID="${invoice.invoice_number}@krow.com" timestamp="${new Date().toISOString()}">
  <Header>
    <From><Credential domain="DUNS"><Identity>KROW</Identity></Credential></From>
    <To><Credential domain="DUNS"><Identity>${business?.erp_vendor_id || 'CLIENT'}</Identity></Credential></To>
    <Sender><Credential domain="DUNS"><Identity>KROW</Identity></Credential></Sender>
  </Header>
  <Request>
    <InvoiceDetailRequest>
      <InvoiceDetailRequestHeader invoiceID="${invoice.invoice_number}" invoiceDate="${invoice.issue_date}" purpose="standard">
        <InvoiceDetailHeaderIndicator/>
        <InvoicePartner><Contact role="billTo"><Name>${invoice.business_name}</Name></Contact></InvoicePartner>
        <PaymentTerm payInNumberOfDays="30"/>
      </InvoiceDetailRequestHeader>
      <InvoiceDetailOrder>
        <InvoiceDetailOrderInfo><OrderReference orderID="${invoice.po_reference || ''}"/></InvoiceDetailOrderInfo>
        <InvoiceDetailItem invoiceLineNumber="1" quantity="1">
          <UnitOfMeasure>EA</UnitOfMeasure>
          <UnitPrice><Money currency="USD">${invoice.amount}</Money></UnitPrice>
          <InvoiceDetailItemReference lineNumber="1"><Description>${invoice.event_name}</Description></InvoiceDetailItemReference>
        </InvoiceDetailItem>
      </InvoiceDetailOrder>
      <InvoiceDetailSummary>
        <SubtotalAmount><Money currency="USD">${invoice.subtotal || invoice.amount}</Money></SubtotalAmount>
        <Tax><Money currency="USD">${invoice.tax_amount || 0}</Money></Tax>
        <GrossAmount><Money currency="USD">${invoice.amount}</Money></GrossAmount>
        <InvoiceDetailDiscount/>
        <NetAmount><Money currency="USD">${invoice.amount}</Money></NetAmount>
        <DueAmount><Money currency="USD">${invoice.amount}</Money></DueAmount>
      </InvoiceDetailSummary>
    </InvoiceDetailRequest>
  </Request>
</cXML>`;
  };

  const generateCSV = () => {
    const headers = [
      "Invoice Number", "Invoice Date", "Due Date", "PO Number", "Vendor ID",
      "Client Name", "Hub", "Event Name", "Cost Center", "Subtotal", "Tax", "Total Amount", "Status"
    ];
    const row = [
      invoice.invoice_number,
      invoice.issue_date,
      invoice.due_date,
      invoice.po_reference || "",
      business?.erp_vendor_id || "",
      invoice.business_name,
      invoice.hub || "",
      invoice.event_name,
      business?.erp_cost_center || "",
      invoice.subtotal || invoice.amount,
      invoice.tax_amount || 0,
      invoice.amount,
      invoice.status
    ];
    
    // Add line items if available
    let lineItems = "\n\nLine Item Details\nRole,Staff Name,Date,Hours,Rate,Amount\n";
    if (invoice.roles) {
      invoice.roles.forEach(role => {
        role.staff_entries?.forEach(entry => {
          lineItems += `${role.role_name},${entry.staff_name},${entry.date},${entry.worked_hours},${entry.rate},${entry.total}\n`;
        });
      });
    }
    
    return headers.join(",") + "\n" + row.join(",") + lineItems;
  };

  const generateJSON = () => {
    return JSON.stringify({
      invoice: {
        invoice_number: invoice.invoice_number,
        issue_date: invoice.issue_date,
        due_date: invoice.due_date,
        po_reference: invoice.po_reference,
        vendor: {
          id: business?.erp_vendor_id,
          name: "KROW Workforce"
        },
        client: {
          name: invoice.business_name,
          hub: invoice.hub,
          cost_center: business?.erp_cost_center
        },
        event: {
          name: invoice.event_name,
          date: invoice.event_date
        },
        amounts: {
          subtotal: invoice.subtotal || invoice.amount,
          tax: invoice.tax_amount || 0,
          total: invoice.amount
        },
        line_items: invoice.roles?.flatMap(role => 
          role.staff_entries?.map(entry => ({
            role: role.role_name,
            staff_name: entry.staff_name,
            date: entry.date,
            hours: entry.worked_hours,
            rate: entry.rate,
            amount: entry.total
          })) || []
        ) || [],
        status: invoice.status
      }
    }, null, 2);
  };

  const handleExport = async (format) => {
    setIsExporting(true);
    
    let content, filename, mimeType;
    
    switch (format) {
      case "EDI 810":
        content = generateEDI810();
        filename = `${invoice.invoice_number}_EDI810.edi`;
        mimeType = "text/plain";
        break;
      case "cXML":
        content = generateCXML();
        filename = `${invoice.invoice_number}.xml`;
        mimeType = "application/xml";
        break;
      case "JSON":
        content = generateJSON();
        filename = `${invoice.invoice_number}.json`;
        mimeType = "application/json";
        break;
      case "CSV":
      default:
        content = generateCSV();
        filename = `${invoice.invoice_number}.csv`;
        mimeType = "text/csv";
        break;
    }
    
    // Create and download file
    const blob = new Blob([content], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    setIsExporting(false);
    setExportSuccess(true);
    setTimeout(() => setExportSuccess(false), 3000);
    
    if (onExport) onExport(format);
  };

  return (
    <Card className="border-slate-200">
      <CardHeader className="pb-3">
        <CardTitle className="text-lg flex items-center gap-2">
          <Link2 className="w-5 h-5 text-blue-600" />
          ERP / EDI Export
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* ERP System Info */}
        {erpSystem !== "None" && (
          <div className="flex items-center justify-between p-3 bg-slate-50 rounded-lg">
            <div className="flex items-center gap-3">
              <Building2 className="w-5 h-5 text-slate-500" />
              <div>
                <p className="text-sm font-medium text-slate-900">Connected ERP</p>
                <p className="text-xs text-slate-500">Vendor ID: {business?.erp_vendor_id || "Not configured"}</p>
              </div>
            </div>
            <Badge className={erpInfo?.color || "bg-slate-100 text-slate-700"}>
              {erpSystem}
            </Badge>
          </div>
        )}

        {/* Export Format Selection */}
        <div className="space-y-2">
          <label className="text-sm font-medium text-slate-700">Export Format</label>
          <Select value={exportFormat} onValueChange={setExportFormat}>
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="CSV">
                <div className="flex items-center gap-2">
                  <FileSpreadsheet className="w-4 h-4" />
                  CSV (Excel Compatible)
                </div>
              </SelectItem>
              <SelectItem value="EDI 810">
                <div className="flex items-center gap-2">
                  <FileText className="w-4 h-4" />
                  EDI 810 (Standard Invoice)
                </div>
              </SelectItem>
              <SelectItem value="cXML">
                <div className="flex items-center gap-2">
                  <Code className="w-4 h-4" />
                  cXML (Ariba/Coupa)
                </div>
              </SelectItem>
              <SelectItem value="JSON">
                <div className="flex items-center gap-2">
                  <Code className="w-4 h-4" />
                  JSON (API Format)
                </div>
              </SelectItem>
            </SelectContent>
          </Select>
        </div>

        {/* Export Buttons */}
        <div className="flex gap-2">
          <Button 
            onClick={() => handleExport(exportFormat)}
            disabled={isExporting}
            className="flex-1 bg-blue-600 hover:bg-blue-700"
          >
            {isExporting ? (
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
            ) : exportSuccess ? (
              <Check className="w-4 h-4 mr-2" />
            ) : (
              <Download className="w-4 h-4 mr-2" />
            )}
            {exportSuccess ? "Exported!" : "Download"}
          </Button>
          
          {business?.invoice_email && (
            <Button 
              variant="outline"
              onClick={() => {/* Send via email logic */}}
              className="border-slate-300"
            >
              <Send className="w-4 h-4 mr-2" />
              Send
            </Button>
          )}
        </div>

        {/* Quick Export Buttons */}
        <div className="pt-2 border-t border-slate-200">
          <p className="text-xs text-slate-500 mb-2">Quick Export</p>
          <div className="flex flex-wrap gap-2">
            <Button variant="outline" size="sm" onClick={() => handleExport("CSV")} className="text-xs">
              <FileSpreadsheet className="w-3 h-3 mr-1" />
              CSV
            </Button>
            <Button variant="outline" size="sm" onClick={() => handleExport("EDI 810")} className="text-xs">
              <FileText className="w-3 h-3 mr-1" />
              EDI
            </Button>
            <Button variant="outline" size="sm" onClick={() => handleExport("cXML")} className="text-xs">
              <Code className="w-3 h-3 mr-1" />
              cXML
            </Button>
            <Button variant="outline" size="sm" onClick={() => handleExport("JSON")} className="text-xs">
              <Code className="w-3 h-3 mr-1" />
              JSON
            </Button>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}