"use client";

import { useState } from "react";

const statuses = [
  { value: "NEW", label: "NEW" },
  { value: "IN_PROGRESS", label: "IN_PROGRESS" },
  { value: "CALL_SCHEDULED", label: "CALL_SCHEDULED" },
  { value: "WON", label: "WON" },
  { value: "LOST", label: "LOST" },
] as const;

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) {
    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(value);
        alert("Не удалось обновить статус");
      }
    } catch {
      setStatus(value);
      alert("Ошибка сети");
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <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>
  );
}