"use client";

import { useState, useEffect, useCallback } from "react";
import { useStorage } from "@/core/storage";
import { v4 as uuid } from "uuid";
import type { ChatMessage, ChatSession, AiProviderConfig } from "../types";

const SESSION_PREFIX = "session:";

export function useChat() {
  const storage = useStorage("ai-chat");
  const [sessions, setSessions] = useState<ChatSession[]>([]);
  const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [sending, setSending] = useState(false);
  const [providerConfig, setProviderConfig] = useState<AiProviderConfig | null>(
    null,
  );

  const activeSession = sessions.find((s) => s.id === activeSessionId) ?? null;

  const refresh = useCallback(async () => {
    setLoading(true);
    const all = await storage.exportAll();
    const results: ChatSession[] = [];
    for (const [key, value] of Object.entries(all)) {
      if (key.startsWith(SESSION_PREFIX) && value) {
        results.push(value as ChatSession);
      }
    }
    results.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
    setSessions(results);
    setLoading(false);
  }, [storage]);

  // Load sessions + check provider config
  // eslint-disable-next-line react-hooks/set-state-in-effect
  useEffect(() => {
    refresh();
    fetch("/api/ai-chat")
      .then((r) => r.json())
      .then((data) => setProviderConfig(data as AiProviderConfig))
      .catch(() => {
        /* silent */
      });
  }, [refresh]);

  const createSession = useCallback(
    async (title?: string, projectTagId?: string, projectName?: string) => {
      const session: ChatSession = {
        id: uuid(),
        title: title || `Conversație ${new Date().toLocaleDateString("ro-RO")}`,
        messages: [],
        createdAt: new Date().toISOString(),
        projectTagId,
        projectName,
      };
      await storage.set(`${SESSION_PREFIX}${session.id}`, session);
      setSessions((prev) => [session, ...prev]);
      setActiveSessionId(session.id);
      return session;
    },
    [storage],
  );

  const updateSession = useCallback(
    async (
      id: string,
      updates: Partial<
        Pick<ChatSession, "title" | "projectTagId" | "projectName">
      >,
    ) => {
      const current = sessions.find((s) => s.id === id);
      if (!current) return;
      const updated = { ...current, ...updates };
      await storage.set(`${SESSION_PREFIX}${id}`, updated);
      setSessions((prev) => prev.map((s) => (s.id === id ? updated : s)));
    },
    [storage, sessions],
  );

  const addMessage = useCallback(
    async (content: string, role: ChatMessage["role"]) => {
      if (!activeSessionId) return;
      const message: ChatMessage = {
        id: uuid(),
        role,
        content,
        timestamp: new Date().toISOString(),
      };
      setSessions((prev) =>
        prev.map((s) => {
          if (s.id !== activeSessionId) return s;
          return { ...s, messages: [...s.messages, message] };
        }),
      );
      // Persist
      const current = sessions.find((s) => s.id === activeSessionId);
      if (current) {
        const updated = {
          ...current,
          messages: [...current.messages, message],
        };
        await storage.set(`${SESSION_PREFIX}${activeSessionId}`, updated);
      }
      return message;
    },
    [storage, activeSessionId, sessions],
  );

  /**
   * Send a user message and get AI response from /api/ai-chat.
   * Falls back to demo mode if provider is not configured.
   */
  const sendMessage = useCallback(
    async (content: string) => {
      if (!activeSessionId || sending) return;

      // Add user message first
      await addMessage(content, "user");
      setSending(true);

      try {
        // Build message history for API from current + the new message
        const current = sessions.find((s) => s.id === activeSessionId);
        const apiMessages = [
          ...(current?.messages ?? []).map((m) => ({
            role: m.role as "user" | "assistant",
            content: m.content,
          })),
          { role: "user" as const, content },
        ];

        // Add project context to system prompt if linked
        let systemPrompt: string | undefined;
        if (current?.projectName) {
          systemPrompt = `Ești un asistent AI pentru biroul de arhitectură. Contextul conversației: proiectul "${current.projectName}". Răspunzi în limba română cu terminologie profesională de arhitectură, urbanism și construcții.`;
        }

        const res = await fetch("/api/ai-chat", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ messages: apiMessages, systemPrompt }),
        });

        if (!res.ok) {
          const err = (await res.json().catch(() => ({}))) as {
            message?: string;
          };
          await addMessage(
            `Eroare API: ${err.message ?? `HTTP ${res.status}`}`,
            "assistant",
          );
          return;
        }

        const data = (await res.json()) as { content: string };
        await addMessage(data.content, "assistant");
      } catch (error) {
        await addMessage(
          `Eroare de conexiune: ${error instanceof Error ? error.message : "necunoscută"}`,
          "assistant",
        );
      } finally {
        setSending(false);
      }
    },
    [activeSessionId, sessions, sending, addMessage],
  );

  const deleteSession = useCallback(
    async (id: string) => {
      await storage.delete(`${SESSION_PREFIX}${id}`);
      setSessions((prev) => prev.filter((s) => s.id !== id));
      if (activeSessionId === id) {
        setActiveSessionId(null);
      }
    },
    [storage, activeSessionId],
  );

  const selectSession = useCallback((id: string) => {
    setActiveSessionId(id);
  }, []);

  return {
    sessions,
    activeSession,
    activeSessionId,
    loading,
    sending,
    providerConfig,
    createSession,
    updateSession,
    sendMessage,
    addMessage,
    deleteSession,
    selectSession,
    refresh,
  };
}
