import { useState, useEffect } from "react";
import { X, Send, Loader2, ShieldCheck, RefreshCw, CheckCircle2 } from "lucide-react";
import { useLanguage } from "@/contexts/LanguageContext";
import { trpc } from "@/lib/trpc";
import { toast } from "sonner";
import { trackContactFormSubmission } from "@/lib/analytics";

export default function RequestQuoteModal() {
  const { lang } = useLanguage();
  const isAr = lang === "ar";
  const [open, setOpen] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [captchaAnswer, setCaptchaAnswer] = useState("");
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    company: "",
    industry: "",
    message: "",
  });

  // Listen for custom event to open modal
  useEffect(() => {
    const handler = (e: Event) => {
      const detail = (e as CustomEvent<{ industry?: string }>).detail;
      if (detail?.industry) {
        setFormData((prev) => ({ ...prev, industry: detail.industry ?? "" }));
      }
      setOpen(true);
      setSubmitted(false);
    };
    window.addEventListener("open-quote-modal", handler);
    return () => window.removeEventListener("open-quote-modal", handler);
  }, []);

  const captchaQuery = trpc.captcha.generate.useQuery(undefined, {
    refetchOnWindowFocus: false,
    staleTime: 4 * 60 * 1000,
    enabled: open,
  });

  const submitMutation = trpc.contact.submit.useMutation({
    onSuccess: () => {
      setSubmitted(true);
      setFormData({ name: "", email: "", company: "", industry: "", message: "" });
      setCaptchaAnswer("");
      trackContactFormSubmission("quote-modal", formData.industry || "general");
      toast.success(isAr ? "تم إرسال طلبك بنجاح!" : "Your quote request has been sent!");
    },
    onError: (error) => {
      captchaQuery.refetch();
      setCaptchaAnswer("");
      toast.error(error.message || (isAr ? "فشل الإرسال. يرجى المحاولة مرة أخرى." : "Failed to send. Please try again."));
    },
  });

  const industries = [
    { value: "Ceramics", label: isAr ? "السيراميك" : "Ceramics" },
    { value: "Glass & Aluminum", label: isAr ? "الزجاج والألمنيوم" : "Glass & Aluminum" },
    { value: "Cement Industry", label: isAr ? "صناعة الأسمنت" : "Cement Industry" },
    { value: "Machinery", label: isAr ? "الآلات" : "Machinery" },
    { value: "Other", label: isAr ? "أخرى" : "Other" },
  ];

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!captchaQuery.data?.id) {
      toast.error(isAr ? "لم يتم تحميل التحقق الأمني." : "CAPTCHA not loaded.");
      return;
    }
    const parsedAnswer = parseInt(captchaAnswer, 10);
    if (isNaN(parsedAnswer)) {
      toast.error(isAr ? "يرجى إدخال رقم صحيح." : "Please enter a valid number.");
      return;
    }
    submitMutation.mutate({
      name: formData.name,
      email: formData.email,
      company: formData.company || undefined,
      industry: formData.industry || undefined,
      message: formData.message || (isAr ? "طلب عرض أسعار" : "Request for quotation"),
      captchaId: captchaQuery.data.id,
      captchaAnswer: parsedAnswer,
    });
  };

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center p-4">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-navy/60 backdrop-blur-sm"
        onClick={() => { if (!submitMutation.isPending) setOpen(false); }}
      />

      {/* Modal */}
      <div className="relative bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="sticky top-0 bg-white border-b border-gray-100 px-6 py-4 flex items-center justify-between rounded-t-2xl z-10">
          <h2 className="font-heading font-bold text-lg text-navy">
            {isAr ? "طلب عرض أسعار" : "Request a Quote"}
          </h2>
          <button
            onClick={() => setOpen(false)}
            disabled={submitMutation.isPending}
            className="p-1.5 rounded-lg hover:bg-gray-100 transition-colors text-gray-400 hover:text-gray-600"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="px-6 py-5">
          {submitted ? (
            <div className="text-center py-8">
              <div className="w-16 h-16 bg-teal/10 rounded-full flex items-center justify-center mx-auto mb-4">
                <CheckCircle2 className="w-8 h-8 text-teal" />
              </div>
              <h3 className="font-heading font-semibold text-xl text-navy mb-2">
                {isAr ? "تم إرسال طلبك!" : "Request Sent!"}
              </h3>
              <p className="text-gray-500 text-sm mb-6">
                {isAr ? "سيتواصل معك فريقنا الهندسي خلال 24 ساعة." : "Our engineering team will get back to you within 24 hours."}
              </p>
              <button
                onClick={() => setOpen(false)}
                className="bg-teal hover:bg-teal-dark text-white font-semibold px-6 py-2.5 rounded-md transition-colors"
              >
                {isAr ? "إغلاق" : "Close"}
              </button>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="space-y-4">
              <p className="text-sm text-gray-500 mb-2">
                {isAr
                  ? "أخبرنا عن احتياجاتك وسيتواصل معك أحد مهندسينا."
                  : "Tell us about your needs and one of our engineers will get back to you."}
              </p>

              <div className="grid sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-medium text-navy/70 mb-1">{isAr ? "الاسم" : "Name"} *</label>
                  <input
                    type="text"
                    required
                    disabled={submitMutation.isPending}
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    className="w-full px-3 py-2 rounded-md border border-gray-200 focus:border-teal focus:ring-2 focus:ring-teal/20 outline-none transition-all text-sm disabled:opacity-50"
                    placeholder={isAr ? "اسمك الكامل" : "Your full name"}
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-navy/70 mb-1">{isAr ? "البريد الإلكتروني" : "Email"} *</label>
                  <input
                    type="email"
                    required
                    disabled={submitMutation.isPending}
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    className="w-full px-3 py-2 rounded-md border border-gray-200 focus:border-teal focus:ring-2 focus:ring-teal/20 outline-none transition-all text-sm disabled:opacity-50"
                    placeholder={isAr ? "بريدك الإلكتروني" : "Your email"}
                  />
                </div>
              </div>

              <div className="grid sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-medium text-navy/70 mb-1">{isAr ? "الشركة" : "Company"}</label>
                  <input
                    type="text"
                    disabled={submitMutation.isPending}
                    value={formData.company}
                    onChange={(e) => setFormData({ ...formData, company: e.target.value })}
                    className="w-full px-3 py-2 rounded-md border border-gray-200 focus:border-teal focus:ring-2 focus:ring-teal/20 outline-none transition-all text-sm disabled:opacity-50"
                    placeholder={isAr ? "اسم الشركة" : "Company name"}
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-navy/70 mb-1">{isAr ? "القطاع" : "Industry"}</label>
                  <select
                    disabled={submitMutation.isPending}
                    value={formData.industry}
                    onChange={(e) => setFormData({ ...formData, industry: e.target.value })}
                    className="w-full px-3 py-2 rounded-md border border-gray-200 focus:border-teal focus:ring-2 focus:ring-teal/20 outline-none transition-all text-sm disabled:opacity-50"
                  >
                    <option value="">{isAr ? "اختر القطاع" : "Select industry"}</option>
                    {industries.map((ind) => (
                      <option key={ind.value} value={ind.value}>{ind.label}</option>
                    ))}
                  </select>
                </div>
              </div>

              <div>
                <label className="block text-xs font-medium text-navy/70 mb-1">{isAr ? "تفاصيل الطلب" : "Request Details"}</label>
                <textarea
                  rows={3}
                  disabled={submitMutation.isPending}
                  value={formData.message}
                  onChange={(e) => setFormData({ ...formData, message: e.target.value })}
                  className="w-full px-3 py-2 rounded-md border border-gray-200 focus:border-teal focus:ring-2 focus:ring-teal/20 outline-none transition-all text-sm disabled:opacity-50 resize-none"
                  placeholder={isAr ? "صف المنتجات أو الخدمات التي تحتاجها..." : "Describe the products or services you need..."}
                />
              </div>

              {/* CAPTCHA */}
              <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
                <div className="flex items-center gap-2 mb-2">
                  <ShieldCheck className="w-3.5 h-3.5 text-teal" />
                  <span className="text-xs font-medium text-navy">{isAr ? "التحقق الأمني" : "Security Check"} *</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="bg-white rounded-md px-3 py-2 font-mono text-base font-bold text-navy tracking-wider select-none border border-gray-200">
                    {captchaQuery.isLoading ? "..." : captchaQuery.data?.question ?? "Error"}
                  </div>
                  <button
                    type="button"
                    onClick={() => { captchaQuery.refetch(); setCaptchaAnswer(""); }}
                    disabled={captchaQuery.isFetching}
                    className="p-1.5 text-gray-400 hover:text-teal transition-colors rounded-md hover:bg-teal/5 disabled:opacity-50"
                  >
                    <RefreshCw className={`w-3.5 h-3.5 ${captchaQuery.isFetching ? "animate-spin" : ""}`} />
                  </button>
                  <input
                    type="text"
                    inputMode="numeric"
                    pattern="[0-9-]*"
                    value={captchaAnswer}
                    onChange={(e) => setCaptchaAnswer(e.target.value)}
                    required
                    disabled={submitMutation.isPending}
                    className="w-20 px-2 py-2 bg-white border border-gray-200 rounded-md text-navy text-center font-mono text-base focus:outline-none focus:ring-2 focus:ring-teal/30 focus:border-teal transition-colors disabled:opacity-50"
                    placeholder="?"
                  />
                </div>
              </div>

              <button
                type="submit"
                disabled={submitMutation.isPending || !captchaQuery.data}
                className="w-full bg-teal hover:bg-teal-dark text-white font-semibold py-2.5 rounded-md transition-all duration-200 hover:shadow-lg hover:shadow-teal/20 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm"
              >
                {submitMutation.isPending ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    {isAr ? "جاري الإرسال..." : "Sending..."}
                  </>
                ) : (
                  <>
                    <Send className="w-4 h-4" />
                    {isAr ? "إرسال طلب عرض الأسعار" : "Send Quote Request"}
                  </>
                )}
              </button>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}
