/**
 * SaveSessionDialog Component
 *
 * Dialog for saving the current import session with a name.
 */

import { useState, useEffect } from 'react';
import { Loader2, Save } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useImportSession } from '@/contexts/ImportSessionContext';
import { toast } from 'sonner';

interface SaveSessionDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  /** Optional suggested name to pre-populate the input */
  suggestedName?: string | null;
  /** Optional callback after successful save */
  onSaved?: () => void;
}

export function SaveSessionDialog({ open, onOpenChange, suggestedName, onSaved }: SaveSessionDialogProps) {
  const { saveAsNamed, sessionName, getSuggestedSessionName } = useImportSession();
  const [name, setName] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [initialized, setInitialized] = useState(false);

  // Initialize name when dialog opens
  useEffect(() => {
    if (open && !initialized) {
      // Priority: existing session name > provided suggested name > auto-generated from data
      const initialName = sessionName || suggestedName || getSuggestedSessionName() || '';
      setName(initialName);
      setInitialized(true);
    }
    // Reset initialized flag when dialog closes
    if (!open) {
      setInitialized(false);
    }
  }, [open, initialized, sessionName, suggestedName, getSuggestedSessionName]);

  const handleSave = async () => {
    const trimmedName = name.trim();
    if (!trimmedName) {
      setError('Please enter a name for the session');
      return;
    }

    try {
      setSaving(true);
      setError(null);
      await saveAsNamed(trimmedName);
      toast.success('Session saved successfully');
      onOpenChange(false);
      onSaved?.();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save session');
    } finally {
      setSaving(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !saving && name.trim()) {
      handleSave();
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Save className="h-5 w-5" />
            Save Session
          </DialogTitle>
          <DialogDescription>
            Save your current progress with a name so you can restore it later.
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label htmlFor="session-name">Session Name</Label>
            <Input
              id="session-name"
              placeholder="e.g., Spring 2025 Products"
              value={name}
              onChange={(e) => {
                setName(e.target.value);
                setError(null);
              }}
              onKeyDown={handleKeyDown}
              disabled={saving}
              autoFocus
            />
            {error && (
              <p className="text-sm text-destructive">{error}</p>
            )}
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
            Cancel
          </Button>
          <Button onClick={handleSave} disabled={saving || !name.trim()}>
            {saving ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                Saving...
              </>
            ) : (
              <>
                <Save className="h-4 w-4 mr-2" />
                Save
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

/**
 * SaveSessionButton Component
 *
 * A button that opens the save session dialog.
 * Shows current save status.
 */
interface SaveSessionButtonProps {
  className?: string;
}

export function SaveSessionButton({ className }: SaveSessionButtonProps) {
  const [dialogOpen, setDialogOpen] = useState(false);
  const { isSaving, lastSaved, sessionName } = useImportSession();

  return (
    <>
      <div className={`flex items-center gap-2 ${className || ''}`}>
        {lastSaved && (
          <span className="text-xs text-muted-foreground">
            {sessionName ? `Saved as "${sessionName}"` : 'Auto-saved'}{' '}
            {new Date(lastSaved).toLocaleTimeString()}
          </span>
        )}
        {isSaving && (
          <span className="text-xs text-muted-foreground flex items-center gap-1">
            <Loader2 className="h-3 w-3 animate-spin" />
            Saving...
          </span>
        )}
        <Button
          variant="outline"
          size="sm"
          onClick={() => setDialogOpen(true)}
          disabled={isSaving}
        >
          <Save className="h-4 w-4 mr-1" />
          {sessionName ? 'Save As...' : 'Save Session'}
        </Button>
      </div>

      <SaveSessionDialog open={dialogOpen} onOpenChange={setDialogOpen} />
    </>
  );
}
