"use client";

import { innerCardTypes } from "@/types";
import React, { useState, useEffect } from "react";
import axios from "axios";
import { useTranslations } from "next-intl";

interface CarRentalModalProps {
  car: innerCardTypes;
  isOpen: boolean;
  onClose: () => void;
}

export default function CarRentalModal({
  car,
  isOpen,
  onClose,
}: CarRentalModalProps) {
  const t = useTranslations();
  const [userName, setUserName] = useState("");
  const [phone, setPhone] = useState("+998 ");
  const [phoneError, setPhoneError] = useState("");
  const [hours, setHours] = useState<number>(1);
  const [total, setTotal] = useState<number | undefined>(car?.price);

  useEffect(() => {
    if (car.price) setTotal(hours * car.price);
  }, [hours, car.price]);

  const formatPhone = (value: string): string => {
    let digits = value.replace(/\D/g, "");
    if (digits.startsWith("998")) digits = digits.slice(3);
    digits = digits.slice(0, 9);
    let formatted = "+998";
    if (digits.length > 0) formatted += " " + digits.slice(0, 2);
    if (digits.length > 2) formatted += " " + digits.slice(2, 5);
    if (digits.length > 5) formatted += " " + digits.slice(5, 7);
    if (digits.length > 7) formatted += " " + digits.slice(7, 9);
    return formatted;
  };

  const isPhoneValid = (value: string): boolean => {
    const digits = value.replace(/\D/g, "");
    return digits.length === 12;
  };

  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const formatted = formatPhone(e.target.value);
    setPhone(formatted);
    if (phoneError) setPhoneError("");
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!userName || !phone || !hours) {
      alert(t("modal-fill-required"));
      return;
    }

    if (!isPhoneValid(phone)) {
      setPhoneError(t("modal-phone-error"));
      return;
    }

    try {
      const token =
        process.env.NEXT_PUBLIC_TELEGRAM_TOKEN ||
        "7940057045:AAHRFPvgUCo_7pqpXD6uq4li7-_DYx2J96g";
      const chatId = process.env.NEXT_PUBLIC_TELEGRAM_CHAT_ID || "6134458285";

      const message = `
🚗 *Yangi buyurtma!*

👤 Ism: ${userName}
📞 Telefon: ${phone}

🕒 Buyurtma vaqti: ${hours} soat
💰 Umumiy summa: ${total?.toLocaleString("uz-UZ")} UZS

📦 Mashina: ${car.name}
⛽️ Yoqilg'i turi: ${car.fuelType || "Noma'lum"}
⚙️ Dvigatel: ${car.enginePower_hp || "-"}
🚀 Maks tezlik: ${car.maxSpeed_kmh ? car.maxSpeed_kmh + " km/soat" : "-"}

📝 Qo'shimcha ma'lumot: ${car.path || "-"}
      `;

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

      alert(t("modal-success"));
      onClose();
      setUserName("");
      setPhone("+998 ");
      setHours(1);
    } catch (error) {
      console.error("Yuborishda xatolik:", error);
      alert(t("modal-error"));
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
      <div className="bg-white rounded-xl shadow-xl max-w-lg w-full p-6 relative animate-fade-in">
        <button
          className="absolute top-4 right-4 text-gray-500 hover:text-gray-900 text-2xl font-bold transition"
          onClick={onClose}
        >
          ×
        </button>

        <div className="flex flex-col md:flex-row gap-4">
          <div className="flex-1">
            <h2 className="text-2xl font-bold text-gray-800">{car.name}</h2>
            <p className="text-gray-600 mt-2">{car.path}</p>
            <p className="text-gray-700 mt-2 font-semibold">
              {t("modal-hourly-price")}{" "}
              <span className="text-red-600">
                {car.price
                  ? Math.round(Number(car.price)).toLocaleString("ru-RU")
                  : ""}{" "}
                UZS
              </span>
            </p>
          </div>
        </div>

        <form onSubmit={handleSubmit} className="mt-6 space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {t("modal-name-label")}
            </label>
            <input
              type="text"
              name="userName"
              className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent"
              value={userName}
              onChange={(e) => setUserName(e.target.value)}
              placeholder={t("modal-name-placeholder")}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {t("modal-phone-label")}
            </label>
            <input
              type="tel"
              name="phone"
              className={`w-full border rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent ${phoneError ? "border-red-500" : "border-gray-300"}`}
              value={phone}
              onChange={handlePhoneChange}
              placeholder={t("modal-phone-placeholder")}
            />
            {phoneError && (
              <p className="text-red-500 text-xs mt-1">{phoneError}</p>
            )}
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {t("modal-hours-label")}
            </label>
            <input
              type="number"
              name="hours"
              min={1}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent"
              value={hours}
              onChange={(e) => setHours(Number(e.target.value))}
            />
          </div>

          <div className="text-lg font-semibold text-gray-800 mt-2">
            {t("modal-total")}{" "}
            <span className="text-green-600">
              {total ? Math.round(Number(total)).toLocaleString("ru-RU") : ""}{" "}
              UZS
            </span>
          </div>

          <button
            type="submit"
            className="w-full bg-secondary text-white py-2 rounded-lg hover:bg-primary transition font-medium"
          >
            {t("book")}
          </button>
        </form>
      </div>
    </div>
  );
}
