"use client";

import { useState } from "react";

const statuses = [
  { value: "NEW", label: "Новая" },
  { value: "IN_PROGRESS", label: "В работе" },
  { value: "CALL_SCHEDULED", label: "Назначен звонок" },
  { value: "WON", label: "Успешно" },
  { value: "LOST", label: "Закрыта" },
] as const;

function getStatusDot(value: string) {
  switch (value) {
    case "NEW":
      return "bg-sky-400";
    case "IN_PROGRESS":
      return "bg-amber-400";
    case "CALL_SCHEDULED":
      return "bg-violet-400";
    case "WON":
      return "bg-emerald-400";
    case "LOST":
      return "bg-rose-400";
    default:
      return "bg-neutral-400";
  }
}

export default function LeadStatusSelect({
  leadId,
  value,
}: {
  leadId: string;
  value: string;
}) {
  const [status, setStatus] = useState(value);
  const [isSaving, setIsSaving] = useState(false);

  async function updateStatus(nextStatus: string) {
    const prev = status;
    setStatus(nextStatus);
    setIsSaving(true);

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

      if (!response.ok) {
        setStatus(prev);
        alert("Не удалось обновить статус");
      }
    } catch {
      setStatus(prev);
      alert("Ошибка сети");
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <div className="flex items-center gap-2">
      <span className={`inline-block h-2.5 w-2.5 rounded-full ${getStatusDot(status)}`} />
      <select
        value={status}
        disabled={isSaving}
        onChange={(e) => updateStatus(e.target.value)}
        className="rounded-xl border border-white/10 bg-black/30 px-3 py-2 text-sm outline-none"
      >
        {statuses.map((item) => (
          <option key={item.value} value={item.value}>
            {item.label}
          </option>
        ))}
      </select>
    </div>
  );
}