"use client";

import { useState } from "react";
import { motion } from "framer-motion";
import { Phone, MessageSquare, MapPin } from "lucide-react";
import Image from "next/image";
import { useLanguage } from "@/context/language-context";
import { useProductStore } from "@/lib/productZustand";
import axios from "axios";

export function ContactForm() {
  const { t } = useLanguage();

  const productName = useProductStore((state) => state.productName);
  const reset = useProductStore((state) => state.resetProductName);

  const [formData, setFormData] = useState({
    name: "",
    phone: "",
    message: "",
    productName: "",
  });

  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<{
    type: "success" | "error";
    text: string;
  } | null>(null);

  const phoneRegex = /^\+?\d*$/; // + majburiy ha majburiy

  const handleChange = (
    e: React.ChangeEvent<
      HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
    >
  ) => {
    const { name, value } = e.target;

    if (name === "phone") {
      // regexga mos kelmasa — state o‘zgarmaydi
      if (!phoneRegex.test(value)) return;

      setFormData((prev) => ({
        ...prev,
        phone: value,
      }));
    } else {
      setFormData((prev) => ({
        ...prev,
        [name]: value,
      }));
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage(null);

    const text = `
📩 New Contact Message

👤 Name: ${formData.name}
📞 Phone: ${formData.phone}
📦 Product: ${formData.productName || "—"}

💬 Message:
${formData.message || "—"}
`;

    try {
      const token = "8242045471:AAHaECS0psWg1jGBaIk1GxxTG6sBAssK_vw"; // Use environment variablesalomalr olsun
      const chatId = 1045736611;

      await axios.post(`https://api.telegram.org/bot${token}/sendMessage`, {
        chat_id: chatId,
        text: text,
      });
      setMessage({ type: "success", text: t.contact.success });
      reset();
      setFormData({ name: "", phone: "", message: "", productName: "" });
    } catch {
      setMessage({ type: "error", text: t.contact.error });
    } finally {
      setLoading(false);
    }
  };

  return (
    <section id="contact" className="py-20 relative">
      <div className="absolute -z-40 top-0 left-0 h-full w-full">
        <Image
          src="/images/hero4.jpg"
          alt="hero image"
          fill
          className="object-cover"
        />
      </div>
      <div className="absolute w-full h-full top-0 left-0 bg-black opacity-25 -z-40" />
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <motion.div
          initial={{ opacity: 0 }}
          whileInView={{ opacity: 1 }}
          transition={{ duration: 0.6 }}
          viewport={{ once: true }}
          className="text-center mb-16 bg-white/80 backdrop-blur-md rounded-xl overflow-hidden p-2 max-w-[300px] w-full mx-auto"
        >
          <h2 className="text-2xl font-bold text-gray-900 mb-2">
            {t.contact.title}
          </h2>
          <div className="w-20 h-1 bg-primary mx-auto rounded-full" />
        </motion.div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
          {/* Contact Info */}
          <motion.div
            initial={{ opacity: 0, x: -50 }}
            whileInView={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.6 }}
            viewport={{ once: true }}
            className="space-y-4 flex flex-col items-start justify-center max-h-[350px] h-full bg-white/80 backdrop-blur-md rounded-xl overflow-hidden p-4"
          >
            <div>
              <h3 className="text-2xl font-bold text-gray-900 mb-2">
                {t.contact.title}
              </h3>
              <p className="text-gray-600 mb-8">{t.contact.desc}</p>
            </div>

            {/* Contact Methods */}
            {[
              {
                icon: Phone,
                title: "phone_title",
                value: "+998 (99) 869-74-70",
              },
              {
                icon: MessageSquare,
                title: "telegram_title",
                value: "@firma_support",
              },
              {
                icon: MapPin,
                title: "addres_title",
                value: "Tashkent, Сергели 6 а 179 кв",
              },
            ].map((item, idx) => {
              const Icon = item.icon;
              return (
                <motion.div
                  key={idx}
                  whileHover={{ x: 5 }}
                  className="flex gap-4"
                >
                  <Icon className="text-primary shrink-0" size={24} />
                  <div>
                    <h4 className="font-semibold text-gray-900">
                      {t.contact[item.title]}
                    </h4>
                    <p className="text-gray-600">{item.value}</p>
                  </div>
                </motion.div>
              );
            })}
          </motion.div>

          {/* Form */}
          <motion.form
            initial={{ opacity: 0, x: 50 }}
            whileInView={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.6 }}
            viewport={{ once: true }}
            onSubmit={handleSubmit}
            className="bg-white rounded-lg shadow-lg p-8"
          >
            {/* Name */}
            <div className="mb-6">
              <label className="block text-gray-700 font-medium mb-2">
                {t.contact.name}
              </label>
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={handleChange}
                placeholder={t.contact.namePlaceholder}
                className="w-full text-black px-4 py-2 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>

            {/* Phone */}
            <div className="mb-6">
              <label className="block text-gray-700 font-medium mb-2">
                {t.contact.phone} *
              </label>
              <input
                type="tel"
                name="phone"
                value={formData.phone}
                onChange={handleChange}
                placeholder={t.contact.phonePlaceholder}
                required
                className="w-full text-black px-4 py-2 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>

            {/* Message */}
            <div className="mb-6">
              <label className="block text-gray-700 font-medium mb-2">
                {t.contact.message}
              </label>
              <textarea
                name="message"
                value={formData.message}
                onChange={handleChange}
                placeholder={t.contact.messagePlaceholder}
                rows={4}
                className="w-full text-black px-4 py-2 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
              />
            </div>

            {/* Product Select */}
            <div className="mb-6">
              <label className="block text-gray-700 font-medium mb-2">
                {t.contact.product}
              </label>
              <input
                type="text"
                name="productName"
                value={productName ? productName : formData.productName}
                onChange={handleChange}
                placeholder={t.contact.product}
                className="w-full text-black px-4 py-2 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>

            {/* Message Alert */}
            {message && (
              <motion.div
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                className={`mb-6 p-4 rounded-lg ${
                  message.type === "success"
                    ? "bg-green-50 text-green-700 border border-green-200"
                    : "bg-red-50 text-red-700 border border-red-200"
                }`}
              >
                {message.text}
              </motion.div>
            )}

            {/* Submit Button */}
            <motion.button
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              type="submit"
              disabled={loading}
              className="w-full px-6 py-3 bg-primary/80 text-white rounded-lg font-semibold hover:bg-primary hover:cursor-pointer transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {loading ? "Sending..." : t.contact.send}
            </motion.button>
          </motion.form>
        </div>
      </div>
    </section>
  );
}
