/**
 * CloseConfirmationDialog Component
 *
 * Single dialog shown when user attempts to close the import modal.
 * Named sessions: Save & Exit or Cancel.
 * Unnamed sessions: Keep (autosave), Save with Name (inline input), Discard, or Cancel.
 */

import { useState, useContext, useEffect } from 'react';
import { Loader2, Save, Trash2, ArrowLeft } from 'lucide-react';
import {
  AlertDialog,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogPortal,
  AlertDialogOverlay,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useImportSession } from '@/contexts/ImportSessionContext';
import { AuthContext } from '@/contexts/AuthContext';
import { deleteAutosaveSession, deleteSession as deleteSessionApi } from '@/services/importSessionApi';

interface CloseConfirmationDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onConfirmClose: () => void;
}

export function CloseConfirmationDialog({
  open,
  onOpenChange,
  onConfirmClose,
}: CloseConfirmationDialogProps) {
  const {
    sessionName,
    sessionId,
    isDirty,
    forceSave,
    saveAsNamed,
    clearSession,
    getSuggestedSessionName,
  } = useImportSession();
  const { user } = useContext(AuthContext);

  const [name, setName] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showNameInput, setShowNameInput] = useState(false);

  // Reset state when dialog opens
  useEffect(() => {
    if (open) {
      const suggested = getSuggestedSessionName();
      setName(suggested || '');
      setError(null);
      setShowNameInput(false);
    }
  }, [open, getSuggestedSessionName]);

  // Only use local saving state for disabling buttons — don't block the user
  // from closing just because a background autosave is in progress.
  const isProcessing = saving;

  const handleOpenChange = (newOpen: boolean) => {
    if (newOpen) {
      const suggested = getSuggestedSessionName();
      setName(suggested || '');
      setError(null);
      setShowNameInput(false);
    }
    onOpenChange(newOpen);
  };

  // Save & Exit (for named sessions, or "Keep" for unnamed)
  const handleSaveAndExit = async () => {
    setSaving(true);
    try {
      await forceSave();
      onConfirmClose();
    } catch (err) {
      console.error('Failed to save:', err);
      onConfirmClose();
    } finally {
      setSaving(false);
    }
  };

  // Save with the entered name, then exit
  const handleSaveWithName = async () => {
    const trimmedName = name.trim();
    if (!trimmedName) {
      setError('Enter a name');
      return;
    }
    setSaving(true);
    try {
      await saveAsNamed(trimmedName);
      onConfirmClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save');
    } finally {
      setSaving(false);
    }
  };

  // Discard session and exit
  const handleDiscardAndExit = async () => {
    setSaving(true);
    try {
      if (sessionId) {
        await deleteSessionApi(sessionId);
      } else if (user?.id) {
        await deleteAutosaveSession(user.id);
      }
      clearSession();
      onConfirmClose();
    } catch (err) {
      console.error('Failed to discard session:', err);
      clearSession();
      onConfirmClose();
    } finally {
      setSaving(false);
    }
  };

  // --- Named session: simple save & exit ---
  if (sessionName) {
    return (
      <AlertDialog open={open} onOpenChange={handleOpenChange}>
        <AlertDialogPortal>
          <AlertDialogOverlay className="z-[1400]" />
          <AlertDialogContent className="z-[1500]">
            <AlertDialogHeader>
              <AlertDialogTitle>Exit Import</AlertDialogTitle>
              <AlertDialogDescription>
                {isDirty
                  ? `Your session "${sessionName}" will be saved. You can restore it later from the upload step.`
                  : `Your session "${sessionName}" is saved. You can restore it later from the upload step.`}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel disabled={isProcessing}>Cancel</AlertDialogCancel>
              <Button onClick={handleSaveAndExit} disabled={isProcessing}>
                {isProcessing ? (
                  <><Loader2 className="h-4 w-4 mr-2 animate-spin" />Saving...</>
                ) : (
                  'Save & Exit'
                )}
              </Button>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialogPortal>
      </AlertDialog>
    );
  }

  // --- Unnamed session: all options in one view ---
  return (
    <AlertDialog open={open} onOpenChange={handleOpenChange}>
      <AlertDialogPortal>
        <AlertDialogOverlay className="z-[1400]" />
        <AlertDialogContent className={`z-[1500] ${showNameInput ? 'max-w-[400px]' : 'max-w-[700px]'}`}>
          <AlertDialogHeader>
            <AlertDialogTitle>{showNameInput ? 'Save As...' : 'Exit Product Import'}</AlertDialogTitle>
            <AlertDialogDescription>
              {showNameInput ? 'Enter a name for your session to save it.' : 'Your progress has been auto-saved. You can keep it, save it with a name, or discard it.'}
            </AlertDialogDescription>
          </AlertDialogHeader>

          {/* Inline name input - shown only when user clicks "Save with Name" */}
          {showNameInput && (
            <>
              <div className="flex items-center justify-end gap-2 px-0 py-1">
                <Input
                  placeholder="Session name"
                  value={name}
                  onChange={(e) => { setName(e.target.value); setError(null); }}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' && !isProcessing && name.trim()) {
                      handleSaveWithName();
                    }
                  }}
                  disabled={isProcessing}
                  className="w-[200px]"
                  autoFocus
                />
                <Button
                  onClick={handleSaveWithName}
                  disabled={isProcessing || !name.trim()}
                >
                  {isProcessing ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : (
                    <><Save className="h-4 w-4 mr-1" />Save & Exit</>
                  )}
                </Button>
              </div>
              {error && <p className="text-sm text-destructive">{error}</p>}
            </>
          )}
    {!showNameInput && (
          <AlertDialogFooter className="flex-col sm:flex-row gap-1">
        
              <>
            <AlertDialogCancel disabled={isProcessing} className="mt-0">
              <ArrowLeft className="h-4 w-4" /> Continue Editing
            </AlertDialogCancel>
          
            <Button
              variant="outline"
              onClick={handleDiscardAndExit}
              disabled={isProcessing}
              className="text-destructive hover:text-destructive/90"
            >
              {isProcessing ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Trash2 className="h-4 w-4" />
              )}
              Discard
            </Button>
            <Button
              onClick={() => setShowNameInput(true)}
              disabled={isProcessing || showNameInput}
              variant="outline"
            >
              <Save className="h-4 w-4" />
              Save As...
            </Button>
            <Button onClick={handleSaveAndExit} disabled={isProcessing}>
              {isProcessing ? (
                <><Loader2 className="h-4 w-4 animate-spin" />Saving...</>
              ) : (
                'Keep & Exit'
              )}
            </Button>
            </>
         
          </AlertDialogFooter>   )}
        </AlertDialogContent>
      </AlertDialogPortal>
    </AlertDialog>
  );
}
