"use client";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { useState, useEffect } from "react";
import { X } from "lucide-react";
import { usePriceModalStore } from "@/zustand/useProceModalStore";
import { useMutation } from "@tanstack/react-query";
import httpClient from "@/request/api";
import { endPoints } from "@/request/links";
import { toast } from "react-toastify";

interface FormType {
  name: string;
  product: number;
  number: number; // ✅ String bo'lishi kerak
}

export function PriceModal() {
  const t = useTranslations("priceModal");
  const { isOpen, product, closeModal } = usePriceModalStore();

  const [formData, setFormData] = useState({
    name: "",
    number: "+998 ",
  });

  const [errors, setErrors] = useState({
    name: "",
    number: "",
  });

  const formRequest = useMutation({
    mutationFn: (data: FormType) =>
      httpClient.post(endPoints.post.productContact, data),
    onSuccess: () => {
      setFormData({
        name: "",
        number: "+998 ",
      });
      toast.success(t("success") || "Muvaffaqiyatli yuborildi!");
      closeModal();
    },
    onError: (error) => {
      console.error("Error:", error);
      toast.error(t("error") || "Xatolik yuz berdi");
    },
  });

  // Reset form when modal closes for github
  useEffect(() => {
    if (!isOpen) {
      setFormData({
        name: "",
        number: "+998 ",
      });
      setErrors({
        name: "",
        number: "",
      });
    }
  }, [isOpen]);

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "unset";
    }
    return () => {
      document.body.style.overflow = "unset";
    };
  }, [isOpen]);

  const formatPhoneNumber = (value: string) => {
    const numbers = value.replace(/\D/g, "");
    if (!numbers.startsWith("998")) {
      return "+998 ";
    }

    let formatted = "+998 ";
    const rest = numbers.slice(3);
    if (rest.length > 0) formatted += rest.slice(0, 2);
    if (rest.length > 2) formatted += " " + rest.slice(2, 5);
    if (rest.length > 5) formatted += " " + rest.slice(5, 7);
    if (rest.length > 7) formatted += " " + rest.slice(7, 9);

    return formatted;
  };

  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const formatted = formatPhoneNumber(e.target.value);
    setFormData({ ...formData, number: formatted });
    if (errors.number) {
      setErrors({ ...errors, number: "" });
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
    if (errors[name as keyof typeof errors]) {
      setErrors({ ...errors, [name]: "" });
    }
  };

  const validateForm = () => {
    const newErrors = {
      name: "",
      number: "",
    };

    // Name validation
    if (!formData.name.trim()) {
      newErrors.name = t("validation.nameRequired") || "Ism kiritilishi shart";
    }

    // Phone validation
    const phoneNumbers = formData.number.replace(/\D/g, "");
    if (phoneNumbers.length !== 12) {
      newErrors.number =
        t("validation.phoneRequired") || "To'liq telefon raqam kiriting";
    } else if (!phoneNumbers.startsWith("998")) {
      newErrors.number =
        t("validation.phoneInvalid") || "Noto'g'ri telefon raqam";
    }

    setErrors(newErrors);
    return !newErrors.name && !newErrors.number;
  };

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

    if (!validateForm()) {
      return;
    }

    // Telefon raqamni tozalash (faqat raqamlar)
    const cleanPhone = formData.number.replace(/\D/g, "");

    const sendedData: FormType = {
      name: formData.name,
      number: Number(cleanPhone.slice(3)), // ✅ String sifatida yuborish
      product: product?.id || 0,
    };
    formRequest.mutate(sendedData);
  };

  if (!isOpen || !product) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
        onClick={closeModal}
      />

      {/* Modal */}
      <div className="relative bg-[#2a2a2a] rounded-2xl shadow-2xl w-full max-w-md max-h-[90vh] overflow-y-auto">
        {/* Close button */}
        <button
          onClick={closeModal}
          className="absolute right-4 top-4 text-gray-400 hover:text-white transition-colors z-10"
          aria-label="Close modal"
        >
          <X size={24} />
        </button>

        {/* Content */}
        <div className="p-6 md:p-8">
          <h2 className="text-2xl md:text-3xl font-bold text-white mb-6">
            {t("title") || "Narx so'rash"}
          </h2>

          {/* Product Info */}
          <div className="bg-[#1e1e1e] rounded-lg p-4 mb-6 flex items-center gap-4">
            <div className="relative w-20 h-20 shrink-0 bg-white rounded-lg overflow-hidden">
              <Image
                src={product.image || "/placeholder.svg"}
                alt={product.name}
                fill
                className="object-contain p-2"
              />
            </div>
            <div className="flex-1">
              <h3 className="text-white font-semibold mb-1 line-clamp-2">
                {product.name}
              </h3>
              <span className="text-green-400 text-sm">
                {product.inStock
                  ? t("product.inStock") || "Sotuvda mavjud"
                  : t("product.outOfStock") || "Sotuvda yo'q"}
              </span>
            </div>
          </div>

          {/* Form */}
          <form onSubmit={handleSubmit} className="space-y-5">
            {/* Name */}
            <div>
              <label
                htmlFor="name"
                className="block text-sm font-medium text-gray-300 mb-2"
              >
                {t("form.name") || "Ismingiz"}
              </label>
              <input
                type="text"
                id="name"
                name="name"
                value={formData.name}
                onChange={handleInputChange}
                className={`w-full px-4 py-3 bg-[#1e1e1e] border ${
                  errors.name ? "border-red-500" : "border-gray-700"
                } rounded-lg text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-red-700 transition`}
                placeholder={t("form.namePlaceholder") || "Ismingizni kiriting"}
              />
              {errors.name && (
                <p className="mt-1 text-sm text-red-500">{errors.name}</p>
              )}
            </div>

            {/* Phone */}
            <div>
              <label
                htmlFor="phone"
                className="block text-sm font-medium text-gray-300 mb-2"
              >
                {t("form.phone") || "Telefon raqam"}
              </label>
              <input
                type="tel"
                id="phone"
                name="phone"
                value={formData.number}
                onChange={handlePhoneChange}
                className={`w-full px-4 py-3 bg-[#1e1e1e] border ${
                  errors.number ? "border-red-500" : "border-gray-700"
                } rounded-lg text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-red-700 transition`}
                placeholder="+998 90 123 45 67"
                maxLength={17}
              />
              {errors.number && (
                <p className="mt-1 text-sm text-red-500">{errors.number}</p>
              )}
            </div>

            {/* Submit Button */}
            <button
              type="submit"
              disabled={formRequest.isPending}
              className="w-full bg-red-700 hover:bg-red-800 disabled:bg-gray-600 disabled:cursor-not-allowed text-white font-bold py-3 px-6 rounded-lg transition-all duration-300 transform hover:scale-105 disabled:hover:scale-100"
            >
              {formRequest.isPending
                ? t("form.submitting") || "Yuborilmoqda..."
                : t("form.submit") || "Yuborish"}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}
