import React, { useState, useEffect } from 'react';
import {
  Upload,
  RefreshCw,
  Loader2,
  CheckCircle2,
  XCircle,
  Database,
  Trash2,
} from 'lucide-react';
import { Button } from '../../components/ui/button';
import { Alert, AlertDescription } from '../../components/ui/alert';
import { Badge } from '../../components/ui/badge';
import type { BackupEntry } from '../../types';
import { useBackupRestore } from '../BackupRestoreContext';

function formatDate(iso: string): string {
  const d = new Date(iso);
  return d.toLocaleString(undefined, {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

export const ExportStep: React.FC = () => {
  const { currentStep } = useBackupRestore();
  const [backups, setBackups] = useState<BackupEntry[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [exportingId, setExportingId] = useState<string | null>(null);
  const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
  const [result, setResult] = useState<{ success: boolean; message: string } | null>(null);

  const loadBackups = async () => {
    setIsLoading(true);
    try {
      const list = await window.backupRestoreAPI.getBackups();
      setBackups(list);
    } catch (err) {
      console.error('Failed to load backups:', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (currentStep === 'export' && !exportingId) {
      loadBackups();
    }
  }, [currentStep]);

  const handleDelete = async (id: string) => {
    try {
      await window.backupRestoreAPI.deleteBackup(id);
      setBackups((prev) => prev.filter((b) => b.id !== id));
    } catch (err) {
      console.error('Failed to delete backup:', err);
    } finally {
      setConfirmDeleteId(null);
    }
  };

  const handleExport = async (backup: BackupEntry) => {
    setExportingId(backup.id);
    setResult(null);
    try {
      const res = await window.backupRestoreAPI.exportBackup(backup.id);
      setResult(res);
    } catch (err: any) {
      setResult({ success: false, message: err.message || 'Export failed' });
    } finally {
      setExportingId(null);
    }
  };

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex items-center gap-3">
        <div className="p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
          <Upload className="h-6 w-6 text-blue-600 dark:text-blue-400" />
        </div>
        <div>
          <h2 className="text-xl font-semibold text-foreground">Export Backup</h2>
          <p className="text-sm text-muted-foreground">
            Export a backup as a portable .zip file you can share or archive.
          </p>
        </div>
      </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>
      )}

      {/* Backup list */}
      <div className="bg-card border border-border rounded-lg overflow-hidden">
        <div className="flex items-center justify-between px-4 py-3 border-b border-border">
          <h3 className="text-sm font-medium text-foreground">Available Backups</h3>
          <Button
            variant="ghost"
            size="sm"
            onClick={loadBackups}
            disabled={isLoading || !!exportingId}
            className="h-7 w-7 p-0"
            title="Refresh backup list"
          >
            <RefreshCw className={`h-3.5 w-3.5 ${isLoading ? 'animate-spin' : ''}`} />
          </Button>
        </div>

        {isLoading ? (
          <div className="flex items-center gap-2 px-4 py-6 text-sm text-muted-foreground">
            <Loader2 className="h-4 w-4 animate-spin" />
            Loading backups…
          </div>
        ) : backups.length === 0 ? (
          <div className="flex flex-col items-center gap-2 px-4 py-8 text-center">
            <Database className="h-8 w-8 text-muted-foreground/40" />
            <p className="text-sm text-muted-foreground">No backups found.</p>
            <p className="text-xs text-muted-foreground">
              Create a backup first using the Backup tab.
            </p>
          </div>
        ) : (
          <ul className="divide-y divide-border">
            {backups.map((backup) => {
              const isExporting = exportingId === backup.id;
              const anyExporting = !!exportingId;

              return (
                <li key={backup.id} className="px-4 py-4 space-y-2">
                  {/* Row 1: date + container badge */}
                  <div className="flex items-center gap-2 min-w-0">
                    <span className="text-sm font-medium text-foreground whitespace-nowrap">
                      {formatDate(backup.createdAt)}
                    </span>
                    <Badge variant="outline" className="shrink-0 font-mono text-xs">
                      {backup.containerName}
                    </Badge>
                    {backup.isDefault && (
                      <Badge variant="secondary" className="shrink-0 text-xs">
                        Default
                      </Badge>
                    )}
                  </div>

                  {/* Row 2: notes */}
                  {backup.notes && (
                    <p className="text-xs text-muted-foreground leading-relaxed">
                      {backup.notes}
                    </p>
                  )}

                  {/* Row 3: actions */}
                  <div className="flex items-center gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleExport(backup)}
                      disabled={anyExporting}
                      className="h-7 text-xs gap-1.5"
                    >
                      {isExporting ? (
                        <>
                          <Loader2 className="h-3.5 w-3.5 animate-spin" />
                          Exporting…
                        </>
                      ) : (
                        <>
                          <Upload className="h-3.5 w-3.5" />
                          Export
                        </>
                      )}
                    </Button>

                    {confirmDeleteId === backup.id ? (
                      <>
                        <span className="text-xs text-muted-foreground">Delete?</span>
                        <Button
                          size="sm"
                          variant="destructive"
                          onClick={() => handleDelete(backup.id)}
                          disabled={anyExporting}
                          className="h-7 text-xs"
                        >
                          Confirm
                        </Button>
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => setConfirmDeleteId(null)}
                          className="h-7 text-xs"
                        >
                          Cancel
                        </Button>
                      </>
                    ) : (
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => setConfirmDeleteId(backup.id)}
                        disabled={anyExporting}
                        className="h-7 text-xs text-muted-foreground hover:text-destructive gap-1.5"
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                        Delete
                      </Button>
                    )}
                  </div>
                </li>
              );
            })}
          </ul>
        )}
      </div>
    </div>
  );
};
