"use client";

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

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

export default function CarRentalModal({
  car,
  isOpen,
  onClose,
}: CarRentalModalProps) {
  const [userName, setUserName] = useState("");
  const [phone, setPhone] = 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]);

  // 🧩 Telegramga yuboruvchi funksiya
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!userName || !phone || !hours) {
      alert("Iltimos, barcha maydonlarni to‘ldiring!");
      return;
    }

    try {
      // ⚙️ Telegram bot ma'lumotlari
      const token =
        process.env.NEXT_PUBLIC_TELEGRAM_TOKEN ||
        "7940057045:AAHRFPvgUCo_7pqpXD6uq4li7-_DYx2J96g";
      const chatId = process.env.NEXT_PUBLIC_TELEGRAM_CHAT_ID || "6134458285";

      // 🧾 Yuboriladigan xabar
      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 || "-"}
      `;

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

      alert("✅ Buyurtmangiz muvaffaqiyatli yuborildi!");
      onClose();
      setUserName("");
      setPhone("");
      setHours(1);
    } catch (error) {
      console.error("Yuborishda xatolik:", error);
      alert("❌ Xatolik yuz berdi. Qayta urinib ko‘ring!");
    }
  };

  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">
        {/* Close button */}
        <button
          className="absolute top-4 right-4 text-gray-500 hover:text-gray-900 text-2xl font-bold transition"
          onClick={onClose}
        >
          ×
        </button>

        {/* Header */}
        <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">
              Soatlik narx:{" "}
              <span className="text-red-600">
                {car.price?.toLocaleString()} UZS
              </span>
            </p>
          </div>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="mt-6 space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Ismingiz
            </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="Ismingizni kiriting"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Telefon
            </label>
            <input
              type="tel"
              name="phone"
              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={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="+998 90 123 45 67"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Qancha vaqt (soat)
            </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">
            Jami summa:{" "}
            <span className="text-green-600">
              {total?.toLocaleString()} UZS
            </span>
          </div>

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