import React, { createContext, useContext, useState, useEffect } 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;
}

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;
}

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);

  useEffect(() => {
    setAreasLoading(true);
    setAreasError(null);
    areasService.listarTotal()
      .then((data) => {
        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?.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));
  }, []);

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

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