import React, { useEffect, useState } from 'react';
import clsx from 'clsx';
import { fetchSessions, createSession, deleteSession, updateSession, type ChatSession } from '@/api/ai';

interface SessionListProps {
  activeSessionId: string | null;
  onSelectSession: (id: string) => void;
  isSidebar?: boolean;
  className?: string;
}

export function SessionList({ activeSessionId, onSelectSession, isSidebar, className }: SessionListProps) {
  const [sessions, setSessions] = useState<ChatSession[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadSessions = async () => {
    try {
      setLoading(true);
      const data = await fetchSessions(isSidebar ? true : undefined);
      setSessions(data);
      setError(null);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to load sessions');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadSessions();
  }, [isSidebar]);

  const handleNewChat = async () => {
    try {
      const session = await createSession({ is_sidebar: isSidebar || false });
      setSessions((prev) => [session, ...prev]);
      onSelectSession(session.id);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to create session');
    }
  };

  const handleDelete = async (id: string, e: React.MouseEvent) => {
    e.stopPropagation();
    try {
      await deleteSession(id);
      setSessions((prev) => prev.filter((s) => s.id !== id));
      if (activeSessionId === id) {
        onSelectSession('');
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to delete session');
    }
  };

  if (loading) {
    return <div className="p-4 text-sm text-secondary-400">Laden...</div>;
  }

  return (
    <div className={clsx('flex flex-col h-full', className)}>
      <div className="p-3 border-b border-secondary-200">
        <button
          onClick={handleNewChat}
          className="w-full rounded-lg bg-primary-600 text-white px-3 py-2 text-sm font-medium hover:bg-primary-700"
        >
          + Neuer Chat
        </button>
      </div>
      {error && <div className="p-2 text-xs text-red-600">{error}</div>}
      <div className="flex-1 overflow-y-auto">
        {sessions.length === 0 ? (
          <div className="p-4 text-sm text-secondary-400 text-center">Keine Chats vorhanden</div>
        ) : (
          <ul className="space-y-1 p-2">
            {sessions.map((session) => (
              <li key={session.id}>
                <div
                  onClick={() => onSelectSession(session.id)}
                  className={clsx(
                    'group flex items-center gap-2 rounded-lg px-3 py-2 text-sm cursor-pointer',
                    'hover:bg-secondary-100',
                    activeSessionId === session.id && 'bg-primary-100 text-primary-700'
                  )}
                >
                  <span className="flex-1 truncate">{session.title}</span>
                  <button
                    onClick={(e) => handleDelete(session.id, e)}
                    className="opacity-0 group-hover:opacity-100 text-secondary-400 hover:text-red-600"
                    title="Loeschen"
                  >
                    ✕
                  </button>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}
