/**
 * Export Modal Component
 *
 * Allows users to export their comic in various formats
 * with customizable settings
 */

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

interface ExportModalProps {
  isOpen: boolean;
  onClose: () => void;
}

const EXPORT_FORMATS = [
  {
    value: 'pdf' as const,
    label: 'PDF (Print)',
    description: 'High-quality PDF for printing',
    icon: FileText,
    extension: 'pdf',
  },
  {
    value: 'cbz' as const,
    label: 'CBZ (Digital)',
    description: 'Comic book archive for digital readers',
    icon: Archive,
    extension: 'cbz',
  },
  {
    value: 'png' as const,
    label: 'PNG (Images)',
    description: 'Individual PNG images for each page',
    icon: Image,
    extension: 'zip',
  },
];

const PAGE_SIZES = [
  { value: 'a4', label: 'A4 (210×297mm)', width: 2480, height: 3508 },
  { value: 'letter', label: 'US Letter (8.5×11″)', width: 2550, height: 3300 },
  { value: 'manga', label: 'B5 Manga', width: 2158, height: 3035 },
  { value: 'webtoon', label: 'Webtoon', width: 800, height: 1280 },
  { value: 'square', label: 'Instagram (1:1)', width: 1080, height: 1080 },
];

const DPI_OPTIONS = [
  { value: 72, label: '72 DPI (Web)', description: 'Optimized for web sharing' },
  { value: 150, label: '150 DPI (Draft)', description: 'Good for drafts and previews' },
  { value: 300, label: '300 DPI (Print)', description: 'Professional print quality' },
  { value: 600, label: '600 DPI (High)', description: 'Maximum quality for large prints' },
];

export function ExportModal({ isOpen, onClose }: ExportModalProps): JSX.Element | null {
  const { pageLayouts, panelImages, project } = useComicStore();

  const [selectedFormat, setSelectedFormat] = useState<ExportOptions['format']>('pdf');
  const [pageSize, setPageSize] = useState('a4');
  const [dpi, setDpi] = useState(300);
  const [quality, setQuality] = useState(90);
  const [isExporting, setIsExporting] = useState(false);
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

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

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

    try {
      const options: ExportOptions = {
        format: selectedFormat,
        pageSize,
        dpi,
        quality,
      };

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

      const format = EXPORT_FORMATS.find((f) => f.value === selectedFormat);
      const filename = `${project.projectName || 'comic'}.${format?.extension || 'pdf'}`;

      downloadBlob(blob, filename);
      setSuccess(true);
    } catch (err) {
      console.error('Export failed:', err);
      setError(err instanceof Error ? err.message : 'Export failed. Please try again.');
    } finally {
      setIsExporting(false);
    }
  }, [pageLayouts, panelImages, selectedFormat, pageSize, dpi, quality, project.projectName]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="bg-background rounded-lg shadow-lg max-w-2xl w-full max-h-[90vh] overflow-auto">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b">
          <div>
            <h2 className="text-2xl font-bold flex items-center gap-2">
              <Download className="w-6 h-6" />
              Export Comic
            </h2>
            <p className="text-muted-foreground mt-1">
              Export your comic in various formats
            </p>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-muted rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6 space-y-6">
          {/* Format Selection */}
          <div>
            <h3 className="font-semibold mb-3">Export Format</h3>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              {EXPORT_FORMATS.map((format) => {
                const Icon = format.icon;
                return (
                  <button
                    key={format.value}
                    onClick={() => setSelectedFormat(format.value)}
                    className={`p-4 border rounded-lg text-left transition-all ${
                      selectedFormat === format.value
                        ? 'border-primary bg-primary/5 ring-1 ring-primary'
                        : 'hover:border-primary/50'
                    }`}
                  >
                    <Icon className="w-8 h-8 mb-2 text-primary" />
                    <h4 className="font-medium">{format.label}</h4>
                    <p className="text-xs text-muted-foreground mt-1">
                      {format.description}
                    </p>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Page Size */}
          <div>
            <h3 className="font-semibold mb-3">Page Size</h3>
            <div className="flex flex-wrap gap-2">
              {PAGE_SIZES.map((size) => (
                <button
                  key={size.value}
                  onClick={() => setPageSize(size.value)}
                  className={`px-4 py-2 border rounded-lg text-sm transition-colors ${
                    pageSize === size.value
                      ? 'border-primary bg-primary/10 text-primary'
                      : 'hover:border-primary/50'
                  }`}
                >
                  {size.label}
                </button>
              ))}
            </div>
          </div>

          {/* Quality Settings */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {/* DPI Selection */}
            <div>
              <h3 className="font-semibold mb-3">Resolution (DPI)</h3>
              <div className="space-y-2">
                {DPI_OPTIONS.map((option) => (
                  <button
                    key={option.value}
                    onClick={() => setDpi(option.value)}
                    className={`w-full p-3 border rounded-lg text-left transition-colors ${
                      dpi === option.value
                        ? 'border-primary bg-primary/5'
                        : 'hover:border-primary/50'
                    }`}
                  >
                    <div className="font-medium">{option.label}</div>
                    <div className="text-xs text-muted-foreground">
                      {option.description}
                    </div>
                  </button>
                ))}
              </div>
            </div>

            {/* Quality Slider */}
            <div>
              <h3 className="font-semibold mb-3">Image Quality</h3>
              <div className="p-4 border rounded-lg">
                <div className="flex items-center justify-between mb-2">
                  <span className="text-sm">Compression</span>
                  <span className="text-sm font-medium">{quality}%</span>
                </div>
                <input
                  type="range"
                  min="50"
                  max="100"
                  value={quality}
                  onChange={(e) => setQuality(Number(e.target.value))}
                  className="w-full"
                />
                <div className="flex justify-between text-xs text-muted-foreground mt-1">
                  <span>Smaller file</span>
                  <span>Better quality</span>
                </div>
              </div>

              {/* Summary */}
              <div className="mt-4 p-4 bg-muted/50 rounded-lg">
                <div className="flex items-center gap-2 mb-2">
                  <Settings className="w-4 h-4" />
                  <span className="font-medium">Export Summary</span>
                </div>
                <ul className="text-sm text-muted-foreground space-y-1">
                  <li>Pages: {pageLayouts.length}</li>
                  <li>Format: {selectedFormat.toUpperCase()}</li>
                  <li>Size: {PAGE_SIZES.find((s) => s.value === pageSize)?.label}</li>
                  <li>Resolution: {dpi} DPI</li>
                </ul>
              </div>
            </div>
          </div>

          {/* Error */}
          {error && (
            <div className="p-4 bg-destructive/10 border border-destructive/30 text-destructive rounded-lg">
              {error}
            </div>
          )}

          {/* Success */}
          {success && (
            <div className="p-4 bg-green-50 border border-green-200 text-green-800 rounded-lg flex items-center gap-2">
              <Check className="w-5 h-5" />
              Export complete! File downloaded.
            </div>
          )}

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

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 p-6 border-t bg-muted/50">
          <Button variant="outline" onClick={onClose} disabled={isExporting}>
            Cancel
          </Button>
          <Button
            onClick={handleExport}
            disabled={isExporting || pageLayouts.length === 0}
            className="min-w-[120px]"
          >
            {isExporting ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Exporting...
              </>
            ) : (
              <>
                <Download className="w-4 h-4 mr-2" />
                Export
              </>
            )}
          </Button>
        </div>
      </div>
    </div>
  );
}
