/**
 * Export Section Component
 *
 * Displays export options and a preview of the final comic
 */

import type { JSX } from 'react';
import { useState } from 'react';
import {
  Download,
  FileText,
  Image,
  Archive,
  Check,
  AlertCircle,
  Loader2,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useComicStore } from '@/store/comicStore';
import { exportWithProgress, downloadBlob, type ExportOptions } from '@/services/exportService';
import { PAGE_SIZES } from '@/utils/layoutPatterns';

const EXPORT_FORMATS = [
  {
    value: 'pdf' as const,
    label: 'PDF',
    description: 'Print-ready PDF',
    icon: FileText,
    color: 'bg-red-50 border-red-200 text-red-700',
  },
  {
    value: 'cbz' as const,
    label: 'CBZ',
    description: 'Digital comic archive',
    icon: Archive,
    color: 'bg-blue-50 border-blue-200 text-blue-700',
  },
  {
    value: 'png' as const,
    label: 'PNG',
    description: 'High-res images',
    icon: Image,
    color: 'bg-green-50 border-green-200 text-green-700',
  },
];

export function ExportSection(): JSX.Element {
  const { pageLayouts, panelImages, project, pageSize } = useComicStore();
  const [isExporting, setIsExporting] = useState(false);
  const [exportFormat, setExportFormat] = useState<ExportOptions['format']>('pdf');
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const handleExport = async () => {
    if (pageLayouts.length === 0) {
      setError('No pages to export. Complete the layout first.');
      return;
    }

    setIsExporting(true);
    setProgress(0);
    setError(null);
    setSuccess(false);

    try {
      const options: ExportOptions = {
        format: exportFormat,
        pageSize,
        dpi: 300,
        quality: 90,
      };

      const blob = await exportWithProgress(
        pageLayouts,
        panelImages,
        options,
        setProgress
      );

      const extensions: Record<string, string> = {
        pdf: 'pdf',
        cbz: 'cbz',
        png: 'zip',
      };

      const filename = `${project.projectName || 'comic'}.${extensions[exportFormat]}`;
      downloadBlob(blob, filename);

      setSuccess(true);
    } catch (err) {
      console.error('Export failed:', err);
      setError(err instanceof Error ? err.message : 'Export failed');
    } finally {
      setIsExporting(false);
    }
  };

  const canExport = pageLayouts.length > 0;

  return (
    <div className="max-w-4xl mx-auto space-y-8">
      {/* Header */}
      <div className="text-center space-y-2">
        <h2 className="text-3xl font-bold flex items-center justify-center gap-2">
          <Download className="w-8 h-8" />
          Export Your Comic
        </h2>
        <p className="text-muted-foreground">
          Download your comic in your preferred format
        </p>
      </div>

      {/* Status */}
      {!canExport && (
        <div className="bg-amber-50 border border-amber-200 text-amber-800 px-4 py-3 rounded-lg flex items-center gap-3">
          <AlertCircle className="w-5 h-5" />
          <p>Complete the layout step before exporting.</p>
        </div>
      )}

      {error && (
        <div className="bg-destructive/10 border border-destructive/30 text-destructive px-4 py-3 rounded-lg flex items-center gap-3">
          <AlertCircle className="w-5 h-5" />
          <p>{error}</p>
        </div>
      )}

      {success && (
        <div className="bg-green-50 border border-green-200 text-green-800 px-4 py-3 rounded-lg flex items-center gap-3">
          <Check className="w-5 h-5" />
          <p>Export complete! Your file has been downloaded.</p>
        </div>
      )}

      {/* Export Options */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {EXPORT_FORMATS.map((format) => {
          const Icon = format.icon;
          return (
            <button
              key={format.value}
              onClick={() => setExportFormat(format.value)}
              disabled={!canExport || isExporting}
              className={`p-6 border-2 rounded-xl text-left transition-all ${
                exportFormat === format.value
                  ? format.color
                  : 'border-muted hover:border-primary/50'
              } ${!canExport || isExporting ? 'opacity-50 cursor-not-allowed' : ''}`}
            >
              <Icon className="w-10 h-10 mb-3" />
              <h3 className="text-xl font-bold">{format.label}</h3>
              <p className="text-sm opacity-80 mt-1">{format.description}</p>
            </button>
          );
        })}
      </div>

      {/* Export Settings Summary */}
      {canExport && (
        <div className="bg-muted/50 p-6 rounded-lg border">
          <h3 className="font-semibold mb-4">Export Settings</h3>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            <div>
              <span className="text-muted-foreground">Total Pages</span>
              <p className="font-medium text-lg">{pageLayouts.length}</p>
            </div>
            <div>
              <span className="text-muted-foreground">Page Size</span>
              <p className="font-medium">{PAGE_SIZES[pageSize]?.name || 'A4'}</p>
            </div>
            <div>
              <span className="text-muted-foreground">Resolution</span>
              <p className="font-medium">300 DPI</p>
            </div>
            <div>
              <span className="text-muted-foreground">Format</span>
              <p className="font-medium uppercase">{exportFormat}</p>
            </div>
          </div>
        </div>
      )}

      {/* Progress */}
      {isExporting && (
        <div className="space-y-3">
          <div className="flex items-center justify-center gap-2">
            <Loader2 className="w-5 h-5 animate-spin" />
            <span>Exporting your comic...</span>
          </div>
          <div className="h-2 bg-muted rounded-full overflow-hidden max-w-md mx-auto">
            <div
              className="h-full bg-primary transition-all duration-300"
              style={{ width: `${progress}%` }}
            />
          </div>
          <p className="text-center text-sm text-muted-foreground">
            {Math.round(progress)}% complete
          </p>
        </div>
      )}

      {/* Export Button */}
      <div className="flex justify-center">
        <Button
          size="lg"
          onClick={handleExport}
          disabled={!canExport || isExporting}
          className="min-w-[200px]"
        >
          {isExporting ? (
            <>
              <Loader2 className="w-5 h-5 mr-2 animate-spin" />
              Exporting...
            </>
          ) : (
            <>
              <Download className="w-5 h-5 mr-2" />
              Export Comic
            </>
          )}
        </Button>
      </div>

      {/* Tips */}
      <div className="text-center text-sm text-muted-foreground space-y-1">
        <p>💡 Tip: PDF is best for printing, CBZ for digital readers</p>
        <p>All formats include your page layouts and panel images</p>
      </div>
    </div>
  );
}
