"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { leadStatusLabels, statusTone } from "@/lib/adminLabels";

export default function LeadStatusSelect({ id, status }: { id: number; status: string }) {
  const router = useRouter();
  const [value, setValue] = useState(status);
  const [saving, setSaving] = useState(false);

  const change = async (next: string) => {
    const previous = value;
    setValue(next);
    setSaving(true);
    const res = await fetch(`/api/v1/admin/leads/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: next }),
    }).catch(() => null);
    setSaving(false);
    if (!res?.ok) setValue(previous);
    else router.refresh();
  };

  return (
    <select
      value={value}
      disabled={saving}
      onChange={(e) => change(e.target.value)}
      aria-label="Estado del lead"
      className={`cursor-pointer rounded-full border-0 px-3 py-1 text-xs ${statusTone[value] ?? ""}`}
    >
      {Object.entries(leadStatusLabels).map(([key, label]) => (
        <option key={key} value={key}>
          {label}
        </option>
      ))}
    </select>
  );
}
