"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import type { LicitationReviewStatusView } from "@/lib/licitations/preferences";
import { Button } from "@/components/ui/button";

type LicitationCardActionsProps = {
  licitationId: string;
  initialStatus: LicitationReviewStatusView;
  normativeAnalysisHref: string;
};

type ApiPayload = {
  ok?: boolean;
  error?: string;
  status?: LicitationReviewStatusView;
};

export function LicitationCardActions({ licitationId, initialStatus, normativeAnalysisHref }: LicitationCardActionsProps) {
  const router = useRouter();
  const [status, setStatus] = useState<LicitationReviewStatusView>(initialStatus);
  const [isSaving, setIsSaving] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  async function updateStatus(nextStatus: LicitationReviewStatusView, shouldRefresh = true) {
    setErrorMessage(null);
    setIsSaving(true);

    try {
      const response = await fetch(`/api/licitations/preferences/${encodeURIComponent(licitationId)}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ status: nextStatus }),
      });

      const payload = (await response.json().catch(() => ({}))) as ApiPayload;

      if (!response.ok || !payload.ok || !payload.status) {
        setErrorMessage(payload.error ?? "No fue posible actualizar el estado.");
        return false;
      }

      setStatus(payload.status);
      if (shouldRefresh) {
        router.refresh();
      }
      return true;
    } catch {
      setErrorMessage("No fue posible actualizar el estado.");
      return false;
    } finally {
      setIsSaving(false);
    }
  }

  async function handleToggleReviewed() {
    const nextStatus = status === "REVIEWED" ? "NEW" : "REVIEWED";
    await updateStatus(nextStatus);
  }

  async function handleInterested() {
    const ok = await updateStatus("INTERESTED", false);
    if (!ok) {
      return;
    }
    window.location.href = normativeAnalysisHref;
  }

  async function handleDiscardOrRestore() {
    const nextStatus = status === "DISCARDED" ? "NEW" : "DISCARDED";
    await updateStatus(nextStatus);
  }

  return (
    <div className="space-y-2">
      <div className="flex flex-wrap gap-2">
        <Button size="sm" variant="secondary" onClick={handleToggleReviewed} disabled={isSaving}>
          {status === "REVIEWED" ? "Quitar consultada" : "Marcar consultada"}
        </Button>
        <Button size="sm" onClick={handleInterested} disabled={isSaving}>
          Me interesa
        </Button>
        <Button size="sm" variant="ghost" onClick={handleDiscardOrRestore} disabled={isSaving}>
          {status === "DISCARDED" ? "Restaurar" : "Descartar"}
        </Button>
      </div>
      {errorMessage ? <p className="text-xs font-semibold text-[#b93a4b]">{errorMessage}</p> : null}
    </div>
  );
}
