import React, { useState } from 'react';
import {
  Download,
  FolderOpen,
  Loader2,
  CheckCircle2,
  XCircle,
  FileArchive,
} from 'lucide-react';
import { Button } from '../../components/ui/button';
import { Alert, AlertDescription } from '../../components/ui/alert';

export const ImportStep: React.FC = () => {
  const [selectedFile, setSelectedFile] = useState<string | null>(null);
  const [isImporting, setIsImporting] = useState(false);
  const [result, setResult] = useState<{ success: boolean; message: string } | null>(null);

  const handleSelectFile = async () => {
    const filePath = await window.backupRestoreAPI.selectExportFile();
    if (filePath) {
      setSelectedFile(filePath);
      setResult(null);
    }
  };

  const handleImport = async () => {
    if (!selectedFile) return;
    setIsImporting(true);
    setResult(null);
    try {
      const res = await window.backupRestoreAPI.importBackup(selectedFile);
      setResult(res);
      if (res.success) {
        setSelectedFile(null);
      }
    } catch (err: any) {
      setResult({ success: false, message: err.message || 'Import failed' });
    } finally {
      setIsImporting(false);
    }
  };

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex items-center gap-3">
        <div className="p-2 bg-green-100 dark:bg-green-900/30 rounded-lg">
          <Download className="h-6 w-6 text-green-600 dark:text-green-400" />
        </div>
        <div>
          <h2 className="text-xl font-semibold text-foreground">Import Backup</h2>
          <p className="text-sm text-muted-foreground">
            Import a previously exported backup .zip file into your backup library.
          </p>
        </div>
      </div>

      {/* File selector */}
      <div className="bg-card border border-border rounded-lg p-5 space-y-4">
        <h3 className="text-sm font-medium text-foreground">Select Export File</h3>

        <div
          className="flex items-center gap-3 p-3 rounded-md border border-dashed border-border bg-muted/40 cursor-pointer hover:bg-muted/70 transition-colors"
          onClick={handleSelectFile}
        >
          <FileArchive className="h-8 w-8 text-muted-foreground shrink-0" />
          <div className="min-w-0 flex-1">
            {selectedFile ? (
              <>
                <p className="text-xs font-medium text-foreground truncate">
                  {selectedFile.split('/').pop()}
                </p>
                <p className="text-xs text-muted-foreground truncate">{selectedFile}</p>
              </>
            ) : (
              <p className="text-sm text-muted-foreground">
                Click to select a Canvas backup export (.zip)
              </p>
            )}
          </div>
          <Button
            variant="outline"
            size="sm"
            className="h-7 text-xs shrink-0"
            onClick={(e) => {
              e.stopPropagation();
              handleSelectFile();
            }}
            disabled={isImporting}
          >
            <FolderOpen className="h-3.5 w-3.5 mr-1.5" />
            Browse
          </Button>
        </div>

        <Button
          onClick={handleImport}
          disabled={!selectedFile || isImporting}
          className="w-full bg-green-600 hover:bg-green-700"
        >
          {isImporting ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Importing…
            </>
          ) : (
            <>
              <Download className="h-4 w-4 mr-2" />
              Import Backup
            </>
          )}
        </Button>
      </div>

      {/* Result alert */}
      {result && (
        <Alert variant={result.success ? 'success' : 'destructive'}>
          <div className="flex items-start gap-2">
            {result.success ? (
              <CheckCircle2 className="h-4 w-4 mt-0.5 shrink-0 text-green-600" />
            ) : (
              <XCircle className="h-4 w-4 mt-0.5 shrink-0" />
            )}
            <AlertDescription className="text-sm whitespace-pre-line">
              {result.message}
            </AlertDescription>
          </div>
        </Alert>
      )}
    </div>
  );
};
