"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 "@/store/useProceModalStore";

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

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

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

  const [captchaCode, setCaptchaCode] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Generate random captcha
  useEffect(() => {
    if (isOpen) {
      const code = Math.random().toString(36).substring(2, 8).toUpperCase();
      setCaptchaCode(code);
    }
  }, [isOpen]);

  // Reset form when modal closes
  useEffect(() => {
    if (!isOpen) {
      setFormData({ name: "", phone: "+998 ", captcha: "" });
      setErrors({ name: "", phone: "", captcha: "" });
    }
  }, [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, phone: formatted });
    if (errors.phone) {
      setErrors({ ...errors, phone: "" });
    }
  };

  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: "",
      phone: "",
      captcha: "",
    };

    if (!formData.name.trim()) {
      newErrors.name = t("validation.nameRequired");
    }

    const phoneNumbers = formData.phone.replace(/\D/g, "");
    if (phoneNumbers.length !== 12) {
      newErrors.phone = t("validation.phoneRequired");
    } else if (!phoneNumbers.startsWith("998")) {
      newErrors.phone = t("validation.phoneInvalid");
    }

    if (!formData.captcha.trim()) {
      newErrors.captcha = t("validation.captchaRequired");
    } else if (formData.captcha.toUpperCase() !== captchaCode) {
      newErrors.captcha = t("validation.captchaRequired");
    }

    setErrors(newErrors);
    return !newErrors.name && !newErrors.phone && !newErrors.captcha;
  };

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

    if (!validateForm()) {
      return;
    }

    setIsSubmitting(true);

    try {
      // API call logikangiz
      await new Promise((resolve) => setTimeout(resolve, 1500));

      // Success
      alert(t("success"));
      closeModal();
    } catch (error) {
      alert(t("error"));
    } finally {
      setIsSubmitting(false);
    }
  };

  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/50"
        onClick={closeModal}
      />

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

        {/* Content */}
        <div className="p-8">
          <h2 className="text-3xl font-bold mb-8">{t("title")}</h2>

          {/* Product Info */}
          <div className="bg-[#f5f0e8] rounded-lg p-6 mb-8 flex items-center gap-6">
            <div className="relative w-24 h-24 shrink-0">
              <Image
                src={product.image}
                alt={product.name}
                fill
                className="object-contain"
              />
            </div>
            <div>
              <h3 className="text-xl font-semibold mb-2">{product.name}</h3>
              <span className="text-green-600 font-medium">
                {t("product.inStock")}
              </span>
            </div>
          </div>

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

            {/* Phone */}
            <div>
              <label htmlFor="phone" className="block text-sm font-medium mb-2">
                {t("form.phone")}
              </label>
              <div className="relative">
                <input
                  type="tel"
                  id="phone"
                  name="phone"
                  value={formData.phone}
                  onChange={handlePhoneChange}
                  placeholder={t("form.phonePlaceholder")}
                  className={`w-full pl-2 pr-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 ${
                    errors.phone ? "border-red-500" : "border-gray-300"
                  }`}
                />
              </div>
              {errors.phone && (
                <p className="text-red-500 text-sm mt-1">{errors.phone}</p>
              )}
            </div>

            {/* Captcha */}
            {/* <div>
              <label htmlFor="captcha" className="block text-sm font-medium mb-2">
                {t("form.captcha")}
              </label>
              <div className="flex gap-4">
                <div className="relative w-40 h-12 bg-linear-to-r from-purple-200 via-pink-200 to-blue-200 rounded-lg flex items-center justify-center">
                  <span className="text-2xl font-bold tracking-widest select-none">
                    {captchaCode}
                  </span>
                  <div className="absolute inset-0 opacity-30">
                    <svg className="w-full h-full">
                      <line x1="0" y1="0" x2="100%" y2="100%" stroke="currentColor" strokeWidth="1" />
                      <line x1="100%" y1="0" x2="0" y2="100%" stroke="currentColor" strokeWidth="1" />
                    </svg>
                  </div>
                </div>
                <input
                  type="text"
                  id="captcha"
                  name="captcha"
                  value={formData.captcha}
                  onChange={handleInputChange}
                  placeholder={t("form.captchaPlaceholder")}
                  className={`flex-1 px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 ${
                    errors.captcha ? "border-red-500" : "border-gray-300"
                  }`}
                />
              </div>
              {errors.captcha && (
                <p className="text-red-500 text-sm mt-1">{errors.captcha}</p>
              )}
            </div> */}

            {/* Submit Button */}
            <button
              type="submit"
              disabled={isSubmitting}
              className="w-full bg-[#8B1538] hover:bg-[#6d1028] text-white font-semibold py-4 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isSubmitting ? t("form.submitting") : t("form.submit")}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}