"use client";

import { useEffect, useRef, useState, useTransition } from "react";
import { EstadoFicha } from "@prisma/client";
import { Check, ChevronDown } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { semanticBadgeClass } from "@/lib/badge-variants";
import { cn } from "@/lib/utils";
import { labelEstadoFicha } from "@/lib/estado-ficha";
import { estadoFichaTone } from "@/lib/state-variants";
import { updateFichaEstadoAction } from "@/server/actions/fichas";

const stateOptions: EstadoFicha[] = [EstadoFicha.EN_REVISION, EstadoFicha.INCOMPLETA, EstadoFicha.COMPLETA];

export function EstadoFichaMenu({
  fichaId,
  value,
  onChange,
}: {
  fichaId?: string;
  value: string;
  onChange: (value: string) => void;
}) {
  const [open, setOpen] = useState(false);
  const [isPending, startTransition] = useTransition();
  const rootRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handlePointerDown(event: MouseEvent) {
      if (!rootRef.current) return;
      if (!rootRef.current.contains(event.target as Node)) {
        setOpen(false);
      }
    }

    document.addEventListener("mousedown", handlePointerDown);
    return () => document.removeEventListener("mousedown", handlePointerDown);
  }, []);

  async function selectState(nextState: EstadoFicha) {
    setOpen(false);
    if (!fichaId) {
      onChange(nextState);
      return;
    }

    startTransition(async () => {
      const result = await updateFichaEstadoAction(fichaId, nextState);
      if (!result.ok) {
        toast.error(result.message);
        return;
      }

      onChange(nextState);
      toast.success(result.message);
    });
  }

  const label = labelEstadoFicha(value) || "Borrador";
  const currentTone = estadoFichaTone(value);

  return (
    <div ref={rootRef} className="relative w-fit">
      <Button
        type="button"
        variant="ghost"
        onClick={() => setOpen((current) => !current)}
        disabled={isPending}
        className={cn("h-9 rounded-full px-4 uppercase tracking-wide shadow-sm", semanticBadgeClass(currentTone, { shape: "pill" }))}
      >
        <span>{label}</span>
        <ChevronDown className="h-4 w-4" />
      </Button>

      {open ? (
        <div className="absolute left-0 z-30 mt-2 w-56 overflow-hidden rounded-md border border-border bg-popover text-popover-foreground shadow-lg">
          {stateOptions.map((option) => {
            const optionLabel = labelEstadoFicha(option);
            const isSelected = value === option;
            return (
              <button
                key={option}
                type="button"
                className={cn(
                  "flex w-full items-center justify-between px-3 py-2 text-left text-sm transition-colors hover:bg-muted",
                  isSelected && "bg-muted font-medium",
                )}
                onClick={() => selectState(option)}
              >
                <span>{optionLabel}</span>
                {isSelected ? <Check className="h-4 w-4 text-muted-foreground" /> : null}
              </button>
            );
          })}
        </div>
      ) : null}
    </div>
  );
}
