import React, { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Checkbox } from "@/components/ui/checkbox";
import { useToast } from "@/components/ui/use-toast";
import {
  Download, FileText, Table, FileSpreadsheet, 
  Printer, Share2, Link, CheckCircle, Loader2
} from "lucide-react";
import ReportPDFPreview from "./ReportPDFPreview";

const EXPORT_FORMATS = [
  { id: 'pdf', label: 'PDF Document', icon: FileText, description: 'Best for sharing and printing', color: 'red' },
  { id: 'excel', label: 'Excel Spreadsheet', icon: FileSpreadsheet, description: 'Editable with formulas', color: 'green' },
  { id: 'csv', label: 'CSV File', icon: Table, description: 'Universal data format', color: 'blue' },
  { id: 'json', label: 'JSON (API)', icon: Link, description: 'For system integration', color: 'purple' },
];

export default function ReportExporter({ 
  open, 
  onClose, 
  reportName, 
  reportData,
  onExport 
}) {
  const { toast } = useToast();
  const [selectedFormat, setSelectedFormat] = useState('pdf');
  const [isExporting, setIsExporting] = useState(false);
  const [exportOptions, setExportOptions] = useState({
    includeCharts: true,
    includeSummary: true,
    includeDetails: true,
    includeFooter: true,
  });

  const handleExport = async () => {
    setIsExporting(true);
    
    try {
      // Simulate export process
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // Generate filename
      const timestamp = new Date().toISOString().split('T')[0];
      const filename = `${reportName?.replace(/\s+/g, '-').toLowerCase() || 'report'}-${timestamp}`;
      
      // Handle different export formats
      let blob;
      let extension;
      
      switch (selectedFormat) {
        case 'json':
          blob = new Blob([JSON.stringify(reportData || {}, null, 2)], { type: 'application/json' });
          extension = 'json';
          break;
        case 'csv':
          // Simple CSV conversion
          const csvContent = convertToCSV(reportData);
          blob = new Blob([csvContent], { type: 'text/csv' });
          extension = 'csv';
          break;
        case 'excel':
        case 'pdf':
        default:
          // For demo, just export as JSON
          blob = new Blob([JSON.stringify(reportData || {}, null, 2)], { type: 'application/json' });
          extension = 'json';
          toast({
            title: "Note",
            description: `${selectedFormat.toUpperCase()} export would be generated server-side. Downloaded as JSON for demo.`,
          });
      }
      
      // Trigger download
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${filename}.${extension}`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      
      toast({
        title: "✅ Export Complete",
        description: `${reportName} has been downloaded`,
      });
      
      onExport?.({ format: selectedFormat, filename });
      onClose();
    } catch (error) {
      toast({
        title: "Export Failed",
        description: error.message,
        variant: "destructive",
      });
    } finally {
      setIsExporting(false);
    }
  };

  const convertToCSV = (data) => {
    if (!data || typeof data !== 'object') return '';
    
    // Handle array of objects
    if (Array.isArray(data) && data.length > 0) {
      const headers = Object.keys(data[0]);
      const rows = data.map(row => 
        headers.map(h => JSON.stringify(row[h] ?? '')).join(',')
      );
      return [headers.join(','), ...rows].join('\n');
    }
    
    // Handle single object
    return Object.entries(data)
      .map(([key, value]) => `${key},${JSON.stringify(value)}`)
      .join('\n');
  };

  const handlePrint = () => {
    const printContent = document.getElementById('report-preview-content');
    if (printContent) {
      const printWindow = window.open('', '_blank');
      printWindow.document.write(`
        <html>
          <head>
            <title>${reportName || 'Report'}</title>
            <style>
              body { font-family: system-ui, -apple-system, sans-serif; margin: 0; padding: 20px; }
              * { box-sizing: border-box; }
            </style>
          </head>
          <body>${printContent.innerHTML}</body>
        </html>
      `);
      printWindow.document.close();
      printWindow.print();
    } else {
      window.print();
    }
    toast({ title: "Print dialog opened" });
  };

  const handleShare = async () => {
    const shareUrl = window.location.href;
    
    if (navigator.share) {
      try {
        await navigator.share({
          title: reportName,
          text: `Check out this ${reportName} report`,
          url: shareUrl,
        });
      } catch (err) {
        // User cancelled or error
      }
    } else {
      await navigator.clipboard.writeText(shareUrl);
      toast({ title: "Link Copied", description: "Report link copied to clipboard" });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Download className="w-5 h-5 text-[#0A39DF]" />
            Export Report
          </DialogTitle>
        </DialogHeader>

        <Tabs value={selectedFormat} onValueChange={setSelectedFormat} className="mt-4">
          <TabsList className="grid grid-cols-4 w-full">
            {EXPORT_FORMATS.map(f => {
              const Icon = f.icon;
              return (
                <TabsTrigger key={f.id} value={f.id} className="text-xs">
                  <Icon className="w-3 h-3 mr-1" />
                  {f.label.split(' ')[0]}
                </TabsTrigger>
              );
            })}
          </TabsList>

          {/* PDF Preview */}
          <TabsContent value="pdf" className="mt-4">
            <div id="report-preview-content" className="max-h-[400px] overflow-y-auto border rounded-lg p-2 bg-slate-100">
              <ReportPDFPreview 
                reportName={reportName} 
                reportData={reportData}
                options={exportOptions}
              />
            </div>
          </TabsContent>

          {/* Excel Preview */}
          <TabsContent value="excel" className="mt-4">
            <div className="border rounded-lg p-4 bg-green-50">
              <div className="flex items-center gap-2 mb-3">
                <FileSpreadsheet className="w-5 h-5 text-green-600" />
                <span className="font-medium text-green-800">Excel Spreadsheet</span>
              </div>
              <div className="bg-white border rounded text-xs">
                <div className="grid grid-cols-4 gap-px bg-slate-200">
                  <div className="bg-green-100 p-2 font-semibold">Category</div>
                  <div className="bg-green-100 p-2 font-semibold">Count</div>
                  <div className="bg-green-100 p-2 font-semibold">Amount</div>
                  <div className="bg-green-100 p-2 font-semibold">%</div>
                  {[
                    ['Kitchen Staff', '45', '$42,500', '34%'],
                    ['Event Servers', '38', '$35,200', '28%'],
                    ['Bartenders', '28', '$28,800', '23%'],
                  ].flat().map((cell, i) => (
                    <div key={i} className="bg-white p-2">{cell}</div>
                  ))}
                </div>
              </div>
              <p className="text-xs text-green-700 mt-2">Includes formulas, pivot tables, and multiple sheets</p>
            </div>
          </TabsContent>

          {/* CSV Preview */}
          <TabsContent value="csv" className="mt-4">
            <div className="border rounded-lg p-4 bg-blue-50">
              <div className="flex items-center gap-2 mb-3">
                <Table className="w-5 h-5 text-blue-600" />
                <span className="font-medium text-blue-800">CSV Data</span>
              </div>
              <pre className="bg-slate-900 text-green-400 p-3 rounded text-[10px] overflow-x-auto">
{`category,count,amount,percentage
"Kitchen Staff",45,42500,34
"Event Servers",38,35200,28
"Bartenders",28,28800,23
"Support Staff",22,18500,15`}
              </pre>
              <p className="text-xs text-blue-700 mt-2">Universal format for any spreadsheet or database</p>
            </div>
          </TabsContent>

          {/* JSON Preview */}
          <TabsContent value="json" className="mt-4">
            <div className="border rounded-lg p-4 bg-purple-50">
              <div className="flex items-center gap-2 mb-3">
                <Link className="w-5 h-5 text-purple-600" />
                <span className="font-medium text-purple-800">JSON (API)</span>
              </div>
              <pre className="bg-slate-900 text-amber-400 p-3 rounded text-[10px] overflow-x-auto max-h-32">
{`{
  "report": "${reportName}",
  "generated": "${new Date().toISOString()}",
  "data": {
    "totalSpend": 125000,
    "fillRate": 94.2,
    "categories": [...]
  }
}`}
              </pre>
              <p className="text-xs text-purple-700 mt-2">For API push and system integration</p>
            </div>
          </TabsContent>
        </Tabs>

        {/* Export Options */}
        <div className="flex items-center gap-4 mt-4 pt-4 border-t flex-wrap">
          <div className="flex items-center gap-3 text-sm">
            {[
              { key: 'includeSummary', label: 'Summary' },
              { key: 'includeCharts', label: 'Charts' },
              { key: 'includeDetails', label: 'Details' },
            ].map(opt => (
              <label key={opt.key} className="flex items-center gap-1 cursor-pointer">
                <Checkbox
                  checked={exportOptions[opt.key]}
                  onCheckedChange={(c) => setExportOptions({ ...exportOptions, [opt.key]: c })}
                />
                <span className="text-xs text-slate-600">{opt.label}</span>
              </label>
            ))}
          </div>
          <div className="ml-auto flex gap-2">
            <Button variant="outline" size="sm" onClick={handlePrint}>
              <Printer className="w-3 h-3 mr-1" />
              Print
            </Button>
            <Button variant="outline" size="sm" onClick={handleShare}>
              <Share2 className="w-3 h-3 mr-1" />
              Share
            </Button>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={onClose}>Cancel</Button>
          <Button 
            onClick={handleExport} 
            className="bg-[#0A39DF]"
            disabled={isExporting}
          >
            {isExporting ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Exporting...
              </>
            ) : (
              <>
                <Download className="w-4 h-4 mr-2" />
                Export {selectedFormat.toUpperCase()}
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}