"use client";

import { useState } from "react";

function normalizePhone(input: string) {
  const digits = input.replace(/\D/g, "");

  if (digits.length === 11 && (digits.startsWith("7") || digits.startsWith("8"))) {
    return `7${digits.slice(1)}`;
  }

  if (digits.length === 10) {
    return `7${digits}`;
  }

  return null;
}

function isValidEmail(email: string) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

export default function LeadForm() {
  const [company, setCompany] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [resultMessage, setResultMessage] = useState("");

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setResultMessage("");

    const normalizedPhone = normalizePhone(phone);
    if (!normalizedPhone) {
      setResultMessage("Введите корректный российский телефон");
      return;
    }

    if (!isValidEmail(email.trim())) {
      setResultMessage("Введите корректный email");
      return;
    }

    setIsSubmitting(true);

    try {
      const response = await fetch("/api/leads", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          company,
          phone: normalizedPhone,
          email,
          message,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        setResultMessage(data.error || "Ошибка отправки");
        return;
      }

      setResultMessage("Заявка отправлена. Мы свяжемся с вами.");
      setCompany("");
      setPhone("");
      setEmail("");
      setMessage("");
    } catch {
      setResultMessage("Не удалось сохранить заявку");
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} className="mt-8 grid gap-4 sm:gap-5">
      <input
        type="text"
        placeholder="Название ЖК, ТСЖ или УК"
        value={company}
        onChange={(e) => setCompany(e.target.value)}
        className="w-full rounded-2xl border border-white/10 bg-black/30 px-5 py-4 outline-none placeholder:text-neutral-500 focus:border-emerald-500"
        required
      />

      <input
        type="tel"
        placeholder="+7 (999) 123-45-67"
        value={phone}
        onChange={(e) => setPhone(e.target.value)}
        className="w-full rounded-2xl border border-white/10 bg-black/30 px-5 py-4 outline-none placeholder:text-neutral-500 focus:border-emerald-500"
        required
      />

      <input
        type="email"
        placeholder="Email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        className="w-full rounded-2xl border border-white/10 bg-black/30 px-5 py-4 outline-none placeholder:text-neutral-500 focus:border-emerald-500"
        required
      />

      <textarea
        placeholder="Опишите текущий шлагбаум и что хотите добавить"
        value={message}
        onChange={(e) => setMessage(e.target.value)}
        className="min-h-32 w-full rounded-2xl border border-white/10 bg-black/30 px-5 py-4 outline-none placeholder:text-neutral-500 focus:border-emerald-500"
      />

      <button
        type="submit"
        disabled={isSubmitting}
        className="inline-flex items-center justify-center rounded-2xl bg-emerald-600 px-6 py-4 text-base font-semibold hover:bg-emerald-500 transition-colors disabled:opacity-60"
      >
        {isSubmitting ? "Отправка..." : "Отправить заявку"}
      </button>

      {resultMessage && (
        <p className="text-sm text-neutral-300">{resultMessage}</p>
      )}
    </form>
  );
}