import React, { createContext, useContext, useState, useEffect, useCallback } from "react";
import { areasService, type AreaItem } from "@/services/areas";
import { toast } from "sonner";

export const DEFAULT_AREAS = [
  "Bate-papo",
  "Imagens",
  "Transcrição de Áudio",
  "Geração de Áudio",
  "Agente de Parecer",
  "Outro",
];

export interface Prompt {
  id: string;
  titulo: string;
  area: string;
  area_id?: string;
  descricao?: string;
  conteudo?: string;
  /** ISO ou string da API (ex.: "2026-04-14 13:58:44"). */
  created_at?: string;
}

export type AreaDescriptions = Record<string, string>;

export type AreaIdByNome = Record<string, string>;

interface PromptsContextValue {
  prompts: Prompt[];
  setPrompts: React.Dispatch<React.SetStateAction<Prompt[]>>;
  areas: string[];
  setAreas: React.Dispatch<React.SetStateAction<string[]>>;
  areaDescriptions: AreaDescriptions;
  setAreaDescriptions: React.Dispatch<React.SetStateAction<AreaDescriptions>>;
  areaItems: AreaItem[];
  areaIdByNome: AreaIdByNome;
  areasLoading: boolean;
  areasError: string | null;
  refreshAreas: () => Promise<void>;
}

const PromptsContext = createContext<PromptsContextValue | null>(null);

export function PromptsProvider({ children }: { children: React.ReactNode }) {
  const [prompts, setPrompts] = useState<Prompt[]>([]);
  const [areas, setAreas] = useState<string[]>(() => [...DEFAULT_AREAS]);
  const [areaDescriptions, setAreaDescriptions] = useState<AreaDescriptions>({});
  const [areaItems, setAreaItems] = useState<AreaItem[]>([]);
  const [areaIdByNome, setAreaIdByNome] = useState<AreaIdByNome>({});
  const [areasLoading, setAreasLoading] = useState(true);
  const [areasError, setAreasError] = useState<string | null>(null);

  const refreshAreas = useCallback(async () => {
    setAreasLoading(true);
    setAreasError(null);
    try {
      const data = await areasService.listarTotal();
      const nomes = data.map((a) => a.nome).sort((a, b) => a.localeCompare(b));
      const descricoes = Object.fromEntries(data.map((a) => [a.nome, a.descricao ?? ""]));
      const byNome = Object.fromEntries(data.map((a) => [a.nome, a.id]));
      setAreas(nomes.length > 0 ? nomes : [...DEFAULT_AREAS]);
      setAreaDescriptions(descricoes);
      setAreaItems(data);
      setAreaIdByNome(byNome);
    } catch (err) {
      const message = (err as { message?: string })?.message ?? "Erro ao carregar áreas";
      console.error("[PromptsContext] areasService.listarTotal falhou:", err);
      setAreasError(message);
      toast.error("Não foi possível carregar as áreas. Verifique a conexão e a chave da API.");
    } finally {
      setAreasLoading(false);
    }
  }, []);

  useEffect(() => {
    refreshAreas();
  }, [refreshAreas]);

  return (
    <PromptsContext.Provider value={{ prompts, setPrompts, areas, setAreas, areaDescriptions, setAreaDescriptions, areaItems, areaIdByNome, areasLoading, areasError, refreshAreas }}>
      {children}
    </PromptsContext.Provider>
  );
}

export function usePrompts() {
  const ctx = useContext(PromptsContext);
  if (!ctx) throw new Error("usePrompts must be used within PromptsProvider");
  return ctx;
}
