/**
 * SavedSessionsList Component
 *
 * Displays a list of saved import sessions on the upload step.
 * Shows named sessions and the previous unnamed session (if exists).
 */

import { useState, useEffect, useContext } from 'react';
import { formatDistanceToNow } from 'date-fns';
import { Loader2, Trash2, RotateCcw, Clock, FileSpreadsheet } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { AuthContext } from '@/contexts/AuthContext';
import { importSessionApi } from '@/services/importSessionApi';
import type { ImportSessionListItem, ImportSession } from '@/types/importSession';

interface SavedSessionsListProps {
  onRestore: (session: ImportSession) => void;
}

export function SavedSessionsList({ onRestore }: SavedSessionsListProps) {
  const { user } = useContext(AuthContext);
  const [sessions, setSessions] = useState<ImportSessionListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [deletingId, setDeletingId] = useState<number | null>(null);
  const [restoringId, setRestoringId] = useState<number | null>(null);
  const [deleteConfirmId, setDeleteConfirmId] = useState<number | null>(null);

  // Fetch sessions on mount
  useEffect(() => {
    if (!user?.id) return;

    async function fetchSessions() {
      try {
        setLoading(true);
        setError(null);
        const result = await importSessionApi.list(user!.id);
        setSessions(result);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load sessions');
      } finally {
        setLoading(false);
      }
    }

    fetchSessions();
  }, [user?.id]);

  // Handle restore
  const handleRestore = async (sessionItem: ImportSessionListItem) => {
    try {
      setRestoringId(sessionItem.id);
      // Fetch full session data
      const fullSession = await importSessionApi.get(sessionItem.id);
      onRestore(fullSession);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to restore session');
    } finally {
      setRestoringId(null);
    }
  };

  // Handle delete
  const handleDelete = async (id: number) => {
    try {
      setDeletingId(id);
      await importSessionApi.delete(id);
      setSessions(prev => prev.filter(s => s.id !== id));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to delete session');
    } finally {
      setDeletingId(null);
      setDeleteConfirmId(null);
    }
  };

  // Separate unnamed (previous) session from named sessions
  const unnamedSession = sessions.find(s => s.name === null);
  const namedSessions = sessions.filter(s => s.name !== null);

  // Don't render anything if no sessions
  if (!loading && sessions.length === 0) {
    return null;
  }

  return (
    <>
      <Card className="mt-8">
        <CardHeader className="pb-3">
          <CardTitle className="text-lg flex items-center gap-2">
            <FileSpreadsheet className="h-5 w-5" />
            Saved Sessions
          </CardTitle>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : error ? (
            <div className="text-sm text-destructive py-4">{error}</div>
          ) : (
            <div className="space-y-2">
              {/* Previous session (unnamed) */}
              {unnamedSession && (
                <SessionRow
                  session={unnamedSession}
                  isPrevious
                  isRestoring={restoringId === unnamedSession.id}
                  isDeleting={deletingId === unnamedSession.id}
                  onRestore={() => handleRestore(unnamedSession)}
                  onDelete={() => setDeleteConfirmId(unnamedSession.id)}
                />
              )}

              {/* Named sessions */}
              {namedSessions.map(session => (
                <SessionRow
                  key={session.id}
                  session={session}
                  isRestoring={restoringId === session.id}
                  isDeleting={deletingId === session.id}
                  onRestore={() => handleRestore(session)}
                  onDelete={() => setDeleteConfirmId(session.id)}
                />
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Delete confirmation dialog */}
      <AlertDialog open={deleteConfirmId !== null} onOpenChange={() => setDeleteConfirmId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Session?</AlertDialogTitle>
            <AlertDialogDescription>
              This will permanently delete this saved session. This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => deleteConfirmId && handleDelete(deleteConfirmId)}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}

interface SessionRowProps {
  session: ImportSessionListItem;
  isPrevious?: boolean;
  isRestoring: boolean;
  isDeleting: boolean;
  onRestore: () => void;
  onDelete: () => void;
}

function SessionRow({
  session,
  isPrevious,
  isRestoring,
  isDeleting,
  onRestore,
  onDelete,
}: SessionRowProps) {
  const timeAgo = formatDistanceToNow(new Date(session.updated_at), { addSuffix: true });

  return (
    
    <div className="flex items-center justify-between p-3 rounded-lg border bg-card hover:bg-accent/50 transition-colors">
      <div className="flex-1 min-w-0">
        <div className="font-medium truncate">
          {isPrevious ? (
            <span className="text-amber-600">Previous session</span>
          ) : (
            session.name
          )}
        </div>
        <div className="flex items-center gap-3 text-sm text-muted-foreground mt-0.5">
          <span className="flex items-center gap-1">
            <Clock className="h-3.5 w-3.5" />
            {timeAgo}
          </span>
          <span>{session.row_count} product{session.row_count !== 1 ? 's' : ''}</span>
        </div>
      </div>
      <div className="flex items-center gap-2 ml-4">
        <Button
          size="sm"
          variant="outline"
          onClick={onRestore}
          disabled={isRestoring || isDeleting}
        >
          {isRestoring ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <>
              <RotateCcw className="h-4 w-4 mr-1" />
              Restore
            </>
          )}
        </Button>
        <Button
          size="sm"
          variant="outline"
          onClick={onDelete}
          disabled={isRestoring || isDeleting}
          className="text-destructive hover:text-destructive/90"
        >
          {isDeleting ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <>
              <Trash2 className="h-4 w-4 mr-1" />
              Delete
            </>
          )}
        </Button>
      </div>
    </div>
  );
}
