"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

type Props = {
  leadCode: string;
};

export default function ConvertLeadButton({
  leadCode,
}: Props) {
  const router = useRouter();
  const [pending, setPending] = useState(false);
  const [error, setError] = useState("");

  async function convertLead() {
    if (pending) return;

    const confirmed = window.confirm(
      `Convert Lead ${leadCode} to a Customer? ` +
        "This will create a Customer record and mark the Lead as converted.",
    );

    if (!confirmed) return;

    setPending(true);
    setError("");

    try {
      const response = await fetch(
        `/api/leads/${encodeURIComponent(leadCode)}/convert`,
        {
          method: "POST",
          credentials: "same-origin",
          cache: "no-store",
          headers: {
            "Content-Type": "application/json",
          },
        },
      );

      const result: {
        success?: boolean;
        clientCode?: string;
        error?: string;
      } = await response.json();

      if (
        response.ok &&
        result.success &&
        result.clientCode
      ) {
        router.push(
          `/admin/customers/${encodeURIComponent(
            result.clientCode,
          )}`,
        );
        router.refresh();
        return;
      }

      if (result.error === "ALREADY_CONVERTED") {
        if (result.clientCode) {
          router.push(
            `/admin/customers/${encodeURIComponent(
              result.clientCode,
            )}`,
          );
          router.refresh();
          return;
        }

        setError("This Lead has already been converted.");
        router.refresh();
        return;
      }

      if (response.status === 401) {
        router.push("/admin/login");
        return;
      }

      setError(
        result.error === "CONCURRENT_CHANGE"
          ? "Lead changed during conversion. Refresh and try again."
          : result.error === "INVALID_LEAD_STATUS"
            ? "This Lead cannot be converted in its current status."
            : result.error === "FORBIDDEN"
              ? "You do not have permission to convert this Lead."
              : "Conversion could not be completed. Please try again.",
      );
    } catch {
      setError(
        "Network error. Check the Lead status before trying again.",
      );
    } finally {
      setPending(false);
    }
  }

  return (
    <div className="flex flex-col gap-2">
      <button
        type="button"
        disabled={pending}
        onClick={convertLead}
        className="rounded-xl bg-[var(--blue)] px-5 py-3 text-sm font-semibold text-white disabled:cursor-not-allowed disabled:opacity-60"
      >
        {pending
          ? "Converting..."
          : "Convert to Customer"}
      </button>

      {error && (
        <p role="alert" className="max-w-xs text-sm text-red-700">
          {error}
        </p>
      )}
    </div>
  );
}
