import { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { ArrowLeft, Sparkles, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { InteractiveHoverButton } from "@/components/ui/interactive-hover-button";
import { ParecerJuridicoGeneratingScreen } from "@/components/parecer-juridico/ParecerJuridicoGeneratingScreen";
import { areasService, type AreaItem } from "@/services/areas";
import { promptsService, type PromptItem } from "@/services/promptsApi";
import { parecerService } from "@/services/parecerApi";
import { playSuccessSound } from "@/utils/sound";
import { toast } from "sonner";

export function ParecerJuridicoFormView() {
  const navigate = useNavigate();

  const [areaItems, setAreaItems] = useState<AreaItem[]>([]);
  const [areasLoading, setAreasLoading] = useState(true);
  const [areasError, setAreasError] = useState(false);

  const [tituloParecer, setTituloParecer] = useState("");
  const [areaId, setAreaId] = useState("");
  const [promptId, setPromptId] = useState("");
  const [conteudoPrompt, setConteudoPrompt] = useState("");
  const [instrucao, setInstrucao] = useState("");
  const [anexo, setAnexo] = useState<File | null>(null);
  const anexoInputRef = useRef<HTMLInputElement>(null);
  const [promptsDaArea, setPromptsDaArea] = useState<PromptItem[]>([]);
  const [loadingPrompts, setLoadingPrompts] = useState(false);
  const [isGenerating, setIsGenerating] = useState(false);

  useEffect(() => {
    setAreasLoading(true);
    setAreasError(false);
    areasService.listarTotal()
      .then((data) => setAreaItems(data))
      .catch(() => setAreasError(true))
      .finally(() => setAreasLoading(false));
  }, []);

  const ANEXO_ACCEPT = ".pdf,.txt";

  const handleAnexoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) {
      setAnexo(null);
      return;
    }
    const ext = file.name.split(".").pop()?.toLowerCase();
    const allowed = ["pdf", "txt"];
    if (!ext || !allowed.includes(ext)) {
      toast.error("Formato não permitido. Use PDF ou TXT.");
      e.target.value = "";
      return;
    }
    setAnexo(file);
  };

  const removerAnexo = () => {
    setAnexo(null);
    if (anexoInputRef.current) anexoInputRef.current.value = "";
  };

  useEffect(() => {
    if (!areaId.trim()) {
      setPromptsDaArea([]);
      setPromptId("");
      setConteudoPrompt("");
      return;
    }
    setPromptId("");
    setConteudoPrompt("");
    setLoadingPrompts(true);
    promptsService.listarPorArea(areaId)
      .then((res) => setPromptsDaArea(res.data ?? []))
      .catch(() => {
        toast.error("Erro ao carregar prompts da área.");
        setPromptsDaArea([]);
      })
      .finally(() => setLoadingPrompts(false));
  }, [areaId]);

  useEffect(() => {
    if (!promptId.trim() || promptsDaArea.length === 0) return;
    const prompt = promptsDaArea.find((p) => p.id === promptId);
    if (prompt) setConteudoPrompt(prompt.conteudo ?? "");
  }, [promptId, promptsDaArea]);

  const canSubmit =
    !isGenerating &&
    tituloParecer.trim().length > 0 &&
    areaId.trim().length > 0 &&
    conteudoPrompt.trim().length > 0;

  const handleGerarParecer = () => {
    const titulo = tituloParecer.trim();
    const area = areaId.trim();
    const prompt = conteudoPrompt.trim();
    const instr = instrucao.trim();

    if (!titulo || !area || !prompt) {
      toast.error("Preencha os campos obrigatórios antes de gerar.");
      return;
    }

    setIsGenerating(true);

    parecerService.gerar({
      titulo,
      area_id: area,
      prompt_id: promptId.trim() || undefined,
      prompt,
      instrucao: instr || undefined,
      anexo: anexo ?? undefined,
    })
      .then((data) => {
        setIsGenerating(false);
        playSuccessSound();
        navigate(`/codex/parecer-juridico/${data.id}`, {
          state: { titulo: data.titulo, conteudoMarkdown: data.conteudo_gerado ?? "" },
        });
      })
      .catch((err) => {
        setIsGenerating(false);
        toast.error(err?.message ?? "Erro ao gerar parecer.");
      });
  };

  const descricaoPromptSelecionado = promptId ? promptsDaArea.find((p) => p.id === promptId)?.descricao?.trim() : "";

  return (
    <>
      {isGenerating && (
        <ParecerJuridicoGeneratingScreen message="A geração pode levar de 5 a 8 minutos. Mantenha esta tela aberta até finalizar." />
      )}
      <div className="flex flex-col h-full bg-background pb-16 md:pb-0">
      <div className="p-3 md:p-6 border-b border-border">
        <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-3 mb-4">
          <div className="flex items-center gap-2">
            <Button variant="ghost" size="icon" onClick={() => navigate("/codex/parecer-juridico")} className="shrink-0">
              <ArrowLeft className="w-4 h-4" />
            </Button>
            <h1 className="text-xl md:text-3xl font-bold text-foreground flex items-center gap-2">
              <Sparkles className="w-5 h-5 md:w-6 md:h-6" />
              Novo Parecer
            </h1>
          </div>
        </div>
      </div>

      <div className="flex-1 overflow-auto p-3 md:p-6">
        <div className="max-w-4xl mx-auto flex flex-col gap-6">
          <div className="space-y-2">
            <Label htmlFor="titulo-parecer" className="flex flex-wrap items-baseline gap-1">
              <span>Título do parecer</span>
              <span className="text-destructive font-semibold" aria-hidden>
                *
              </span>
              <span className="sr-only">obrigatório</span>
            </Label>
            <Input
              id="titulo-parecer"
              value={tituloParecer}
              onChange={(e) => setTituloParecer(e.target.value)}
              placeholder="Ex.: Parecer sobre contrato de prestação de serviços"
              className="w-full"
              required
              aria-required="true"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="area" className="flex flex-wrap items-baseline gap-1">
              <span>Área</span>
              <span className="text-destructive font-semibold" aria-hidden>
                *
              </span>
              <span className="sr-only">obrigatório</span>
            </Label>
            <Select value={areaId || "none"} onValueChange={(v) => setAreaId(v === "none" ? "" : v)} disabled={areasLoading}>
              <SelectTrigger id="area" className="w-full">
                <SelectValue
                  placeholder={
                    areasLoading ? "Carregando áreas..." : areasError ? "Erro ao carregar áreas" : "Selecione a área"
                  }
                />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="none">Selecione a área</SelectItem>
                {areaItems.map((a) => (
                  <SelectItem key={a.id} value={a.id}>
                    {a.nome}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {areasError && (
              <p className="text-sm text-destructive">Não foi possível carregar as áreas. Verifique sua conexão e tente novamente.</p>
            )}
          </div>

          <div className="space-y-2">
            <Label htmlFor="prompt">Prompt da base</Label>
            <Select
              value={promptId || "none"}
              onValueChange={(v) => setPromptId(v === "none" ? "" : v)}
              disabled={!areaId.trim() || loadingPrompts}
            >
              <SelectTrigger id="prompt" className="w-full">
                <SelectValue
                  placeholder={
                    loadingPrompts ? "Carregando..." : promptsDaArea.length === 0 && areaId.trim() ? "Nenhum prompt" : "Selecione o prompt"
                  }
                />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="none">Selecione o prompt</SelectItem>
                {promptsDaArea.map((p) => (
                  <SelectItem key={p.id} value={p.id}>
                    {p.titulo}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {areaId.trim() && !loadingPrompts && promptsDaArea.length === 0 && (
              <p className="text-sm text-muted-foreground">Não há prompts para essa área.</p>
            )}
            {descricaoPromptSelecionado && (
              <p className="text-sm text-muted-foreground mt-1">{descricaoPromptSelecionado}</p>
            )}
          </div>

          <div className="space-y-2">
            <Label htmlFor="conteudo-prompt" className="flex flex-wrap items-baseline gap-1">
              <span>Conteúdo do prompt</span>
              <span className="text-destructive font-semibold" aria-hidden>
                *
              </span>
              <span className="sr-only">obrigatório</span>
            </Label>
            <Textarea
              id="conteudo-prompt"
              value={conteudoPrompt}
              onChange={(e) => setConteudoPrompt(e.target.value)}
              placeholder="Selecione um prompt acima ou edite o conteúdo aqui."
              className="min-h-[200px] resize-y w-full"
              required
              aria-required="true"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="instrucao">Instrução</Label>
            <Textarea
              id="instrucao"
              value={instrucao}
              onChange={(e) => setInstrucao(e.target.value)}
              placeholder="Instruções adicionais para a geração do parecer (opcional)..."
              className="min-h-[100px] resize-y w-full"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="anexo">Anexo</Label>
            <p className="text-xs text-muted-foreground">Formatos permitidos: PDF, TXT.</p>
            <div className="flex flex-col gap-2 w-full">
              <div className="flex items-center gap-2 w-full min-h-10 rounded-md border border-input bg-background px-3 py-2">
                <input
                  ref={anexoInputRef}
                  id="anexo"
                  type="file"
                  accept={ANEXO_ACCEPT}
                  onChange={handleAnexoChange}
                  className="sr-only"
                />
                <Label
                  htmlFor="anexo"
                  className="cursor-pointer shrink-0 rounded-md border-0 bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90"
                >
                  Escolher arquivo
                </Label>
                <span className="text-sm text-muted-foreground truncate flex-1 min-w-0">
                  {anexo ? anexo.name : "Nenhum arquivo escolhido"}
                </span>
                {anexo && (
                  <Button type="button" variant="ghost" size="icon" onClick={removerAnexo} className="h-8 w-8 shrink-0" title="Remover anexo">
                    <X className="w-4 h-4" />
                  </Button>
                )}
              </div>
            </div>
          </div>

          <div className="flex justify-end pt-2">
            <InteractiveHoverButton
              type="button"
              onClick={handleGerarParecer}
              disabled={!canSubmit}
              className="disabled:opacity-50 disabled:pointer-events-none"
            >
              Gerar Parecer
            </InteractiveHoverButton>
          </div>
        </div>
      </div>
    </div>
    </>
  );
}
