"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import Text from "../lib_components/text";
import axios from "axios";
import { FormEvent } from "react";

const normalizePhone = (value: string) => value.replace(/\D/g, "");

const formatPhone = (value: string) => {
  const digits = normalizePhone(value);
  const raw = digits.startsWith("998") ? digits.slice(3) : digits;
  const trimmed = raw.slice(0, 9);

  const parts = [];
  if (trimmed.length > 0) {
    parts.push(trimmed.slice(0, 2));
  }
  if (trimmed.length > 2) {
    parts.push(trimmed.slice(2, 5));
  }
  if (trimmed.length > 5) {
    parts.push(trimmed.slice(5, 7));
  }
  if (trimmed.length > 7) {
    parts.push(trimmed.slice(7, 9));
  }

  return parts.length > 0 ? `+998 ${parts.join(" ")}` : "";
};

const isValidPhone = (value: string) => {
  const digits = normalizePhone(value);
  if (digits === "") {
    return false;
  }
  if (digits.length === 9) {
    return true;
  }
  return /^998\d{9}$/.test(digits);
};

export default function Contact() {
  const t = useTranslations();
  const [phone, setPhone] = useState("");

  const handlePhoneChange = (value: string) => {
    setPhone(formatPhone(value));
  };

  const sendMessage = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (!phone || !isValidPhone(phone)) {
      alert(t("contact-phone-error"));
      return;
    }

    const normalized = normalizePhone(phone);
    const formattedPhone = /^998\d{9}$/.test(normalized)
      ? `+${normalized}`
      : `+998${normalized}`;

    try {
      const token = "7940057045:AAHRFPvgUCo_7pqpXD6uq4li7-_DYx2J96g";
      const chatId = 6134458285;

      if (!token || !chatId) {
        throw new Error("Telegram token yoki chat ID topilmadi!");
      }

      const message = `📞 Yangi kontakt: ${formattedPhone}`;

      await axios.post(`https://api.telegram.org/bot${token}/sendMessage`, {
        chat_id: chatId,
        text: message,
      });

      alert(t("contact-success"));
      setPhone("");
    } catch (error) {
      console.error("Yuborishda xatolik:", error);
      alert(t("contact-error"));
    }
  };

  return (
    <section
      dir="ltr"
      className="relative w-full bg-primary py-20 flex justify-center mt-40 px-4"
    >
      <div className="mx-auto absolute z-20 -top-25 bg-secondary max-w-[1200px] w-full py-10 flex flex-col items-center clip-trapezoid">
        <div
          id="contactClip"
          className="w-full flex flex-col items-center justify-center"
        >
          <h2 className="text-2xl md:text-3xl font-bold text-primary mb-5 text-center">
            <Text txt="contact-h2" />
          </h2>

          <form
            className="flex max-sm:flex-col gap-5 w-full max-w-2xl px-4"
            onSubmit={sendMessage}
          >
            <input
              type="tel"
              name="phone"
              value={phone}
              onChange={(event) => handlePhoneChange(event.target.value)}
              placeholder="+998 "
              required
              className="flex-1 py-3 px-5 bg-white text-gray-600 placeholder-gray-400 text-lg clip-input focus:outline-none"
            />
            <button
              type="submit"
              className="bg-primary sm:-ml-5 text-white sm:px-6 sm:py-3 p-2 text-lg font-medium clip-button"
            >
              {t("call")}
            </button>
          </form>
        </div>
      </div>
    </section>
  );
}
