import React, { useState, useEffect, useRef } from 'react';
import { HardDrive, Loader2, CheckCircle2, XCircle, RefreshCw, Copy, Check } from 'lucide-react';
import { Button } from '../../components/ui/button';
import { Alert, AlertDescription } from '../../components/ui/alert';
import { useBackupRestore } from '../BackupRestoreContext';

export const BackupStep: React.FC = () => {
  const { currentStep } = useBackupRestore();
  const [containers, setContainers] = useState<string[]>([]);
  const [selectedContainer, setSelectedContainer] = useState<string>('');
  const [notes, setNotes] = useState<string>('');
  const [isLoadingContainers, setIsLoadingContainers] = useState(true);
  const [isCreating, setIsCreating] = useState(false);
  const [result, setResult] = useState<{ success: boolean; message: string } | null>(null);
  const [terminalOutput, setTerminalOutput] = useState<string>('');
  const [showTerminal, setShowTerminal] = useState(false);
  const [copiedOutput, setCopiedOutput] = useState<string | null>(null);
  const terminalRef = useRef<HTMLDivElement>(null);

  // Auto-scroll terminal to bottom on new output
  useEffect(() => {
    if (terminalRef.current) {
      terminalRef.current.scrollTop = terminalRef.current.scrollHeight;
    }
  }, [terminalOutput]);

  // Subscribe to streaming backup output
  useEffect(() => {
    const unsubscribe = window.backupRestoreAPI.onBackupOutput((output) => {
      setTerminalOutput((prev) => prev + output);
    });
    return unsubscribe;
  }, []);

  const loadContainers = async () => {
    setIsLoadingContainers(true);
    try {
      const list = await window.backupRestoreAPI.getContainers();
      setContainers(list);
      if (list.length > 0) {
        setSelectedContainer((prev) => prev || list[0]);
      }
    } catch (error) {
      console.error('Failed to get containers:', error);
    } finally {
      setIsLoadingContainers(false);
    }
  };

  useEffect(() => {
    if (currentStep === 'backup' && !isCreating) {
      loadContainers();
    }
  }, [currentStep]);

  const handleCreateBackup = async () => {
    if (!selectedContainer) return;

    setIsCreating(true);
    setResult(null);
    setTerminalOutput('');
    setShowTerminal(true);

    try {
      const res = await window.backupRestoreAPI.createBackup({
        containerName: selectedContainer,
        notes
      });
      setResult(res);
    } catch (error: any) {
      setResult({ success: false, message: error.message || 'Failed to create backup' });
    } finally {
      setIsCreating(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-blue-100 dark:bg-blue-900/30 rounded-lg">
          <HardDrive className="h-6 w-6 text-blue-600 dark:text-blue-400" />
        </div>
        <div>
          <h2 className="text-xl font-semibold text-foreground">Backup Database</h2>
          <p className="text-sm text-muted-foreground">
            Export Canvas PostgreSQL databases to a zip archive.
          </p>
        </div>
      </div>

      {/* Config card */}
      <div className="bg-card border border-border rounded-lg p-5 space-y-5">
        {/* What gets backed up */}
        <div>
          <h3 className="text-sm font-medium text-foreground mb-1">What gets backed up</h3>
          <ul className="text-sm text-muted-foreground space-y-1 list-disc list-inside">
            <li>canvas_production database</li>
            <li>canvas_development database</li>
            <li>canvas_test database</li>
          </ul>
          <p className="text-xs text-muted-foreground mt-2">
            Backups are stored in{' '}
            <code className="bg-muted px-1 rounded">~/.inst-agent/backups/</code>
          </p>
        </div>

        <div className="border-t border-border pt-4 space-y-4">
          {/* Container selector */}
          <div>
            <label className="text-sm font-medium text-foreground block mb-2">
              PostgreSQL Container
            </label>
            <div className="flex items-center gap-2">
              {isLoadingContainers ? (
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Loading containers...
                </div>
              ) : containers.length === 0 ? (
                <div className="flex flex-1 items-center gap-2">
                  <p className="text-sm text-muted-foreground flex-1">
                    No canvas-postgres containers found
                  </p>
                  <Button variant="ghost" size="sm" onClick={loadContainers}>
                    <RefreshCw className="h-3.5 w-3.5" />
                  </Button>
                </div>
              ) : (
                <>
                  <select
                    value={selectedContainer}
                    onChange={(e) => setSelectedContainer(e.target.value)}
                    disabled={isCreating}
                    className="flex-1 bg-background border border-border rounded-md px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"
                  >
                    {containers.map((c) => (
                      <option key={c} value={c}>
                        {c}
                      </option>
                    ))}
                  </select>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={loadContainers}
                    disabled={isCreating}
                    title="Refresh container list"
                  >
                    <RefreshCw className="h-3.5 w-3.5" />
                  </Button>
                </>
              )}
            </div>
          </div>

          {/* Notes textarea */}
          <div>
            <label className="text-sm font-medium text-foreground block mb-2">
              Backup Notes{' '}
              <span className="font-normal text-muted-foreground">(optional)</span>
            </label>
            <textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              disabled={isCreating}
              placeholder="Describe this backup (e.g. 'Before migration', 'Clean state after setup')"
              rows={3}
              className="w-full bg-background border border-border rounded-md px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring resize-none disabled:opacity-50"
            />
          </div>
        </div>

        {/* Action button */}
        <Button
          onClick={handleCreateBackup}
          disabled={!selectedContainer || isCreating || isLoadingContainers}
          className="bg-blue-600 hover:bg-blue-700 w-full"
        >
          {isCreating ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Creating Backup...
            </>
          ) : (
            <>
              <HardDrive className="h-4 w-4 mr-2" />
              Create Backup
            </>
          )}
        </Button>
      </div>

      {/* Terminal output */}
      {showTerminal && (
        <div className="bg-card border border-border rounded-lg p-5 space-y-3">
          <div className="flex items-center justify-between">
            <h3 className="text-sm font-medium text-foreground">Backup Output</h3>
            <button
              onClick={() => { navigator.clipboard.writeText(terminalOutput); setCopiedOutput('backup'); setTimeout(() => setCopiedOutput(null), 2000); }}
              className="p-1 hover:bg-secondary rounded"
              title="Copy output"
            >
              {copiedOutput === 'backup' ? <Check className="h-3.5 w-3.5 text-green-600" /> : <Copy className="h-3.5 w-3.5 text-muted-foreground" />}
            </button>
          </div>
          <div
            ref={terminalRef}
            className="bg-black text-green-400 p-4 rounded font-mono text-xs overflow-auto max-h-80"
            style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}
          >
            {terminalOutput || 'Waiting for output...'}
          </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 flex-shrink-0 text-green-600" />
            ) : (
              <XCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
            )}
            <AlertDescription className="text-sm whitespace-pre-line">
              {result.message}
            </AlertDescription>
          </div>
        </Alert>
      )}
    </div>
  );
};
