import { useState } from "react";
import Layout from "@/components/Layout";
import SEOHead from "@/components/SEOHead";
import { Mail, Phone, MapPin, MessageCircle, Clock, Printer, Send, CheckCircle2, Loader2, RefreshCw, ShieldCheck, Instagram, Linkedin, Facebook } from "lucide-react";
import { useLanguage } from "@/contexts/LanguageContext";
import { toast } from "sonner";
import { trpc } from "@/lib/trpc";
import { trackContactFormSubmission, trackPhoneClick, trackWhatsAppClick } from "@/lib/analytics";

const HERO_IMG = "/images/hero-industrial.jpg";

export default function Contact() {
  const { t, lang } = useLanguage();
  const [submitted, setSubmitted] = useState(false);
  const [captchaAnswer, setCaptchaAnswer] = useState("");

  const contactInfo = [
    { icon: Phone, label: lang === "ar" ? "الهاتف" : "Phone", value: "+971 4 881 4928-9", href: "tel:+97148814928", ltr: true },
    { icon: Printer, label: lang === "ar" ? "فاكس" : "Fax", value: "+971 4 887 3928", href: "", ltr: true },
    { icon: Mail, label: lang === "ar" ? "البريد الإلكتروني" : "Email", value: "info@alzarfze.com", href: "mailto:info@alzarfze.com", ltr: true },
    { icon: MessageCircle, label: lang === "ar" ? "واتساب" : "WhatsApp", value: "+971 55 328 8217", href: "https://wa.me/971553288217", ltr: true },
    { icon: MapPin, label: lang === "ar" ? "العنوان" : "Address", value: lang === "ar" ? "LOB #21، الدوار السادس، ميناء جبل علي، المنطقة الحرة لجبل علي، دبي، الإمارات" : "LOB #21, 6th Roundabout, Mina Jebel Ali, Jebel Ali Free Zone, Dubai, UAE", href: "" },
    { icon: Clock, label: t("contact.workingHours"), value: t("contact.monFriFull"), href: "" },
  ];

  const industries = [
    { value: "ceramics", label: lang === "ar" ? "السيراميك والمواد الخام" : "Ceramics & Raw Materials" },
    { value: "glass", label: lang === "ar" ? "الزجاج والألمنيوم" : "Glass & Aluminum" },
    { value: "cement", label: lang === "ar" ? "صناعة الأسمنت" : "Cement Industry" },
    { value: "machinery", label: lang === "ar" ? "الآلات" : "Machinery" },
    { value: "other", label: lang === "ar" ? "أخرى" : "Other" },
  ];

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

  const submitMutation = trpc.contact.submit.useMutation({
    onSuccess: () => {
      setSubmitted(true);
      setCaptchaAnswer("");
      trackContactFormSubmission("contact-page");
      toast.success(lang === "ar" ? "تم إرسال رسالتك بنجاح! سنتواصل معك قريباً." : "Your message has been sent successfully! We'll get back to you soon.");
    },
    onError: (error) => {
      captchaQuery.refetch();
      setCaptchaAnswer("");
      toast.error(error.message || (lang === "ar" ? "فشل إرسال الرسالة. يرجى المحاولة مرة أخرى." : "Failed to send message. Please try again or contact us via WhatsApp."));
    },
  });

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const name = formData.get("name") as string;
    const email = formData.get("email") as string;
    const company = formData.get("company") as string;
    const industry = formData.get("industry") as string;
    const message = formData.get("message") as string;

    if (!captchaQuery.data?.id) {
      toast.error(lang === "ar" ? "لم يتم تحميل التحقق الأمني. يرجى التحديث والمحاولة مرة أخرى." : "CAPTCHA not loaded. Please refresh and try again.");
      return;
    }

    const parsedAnswer = parseInt(captchaAnswer, 10);
    if (isNaN(parsedAnswer)) {
      toast.error(lang === "ar" ? "يرجى إدخال رقم صحيح للتحقق الأمني." : "Please enter a valid number for the CAPTCHA.");
      return;
    }

    submitMutation.mutate({
      name,
      email,
      company: company || undefined,
      industry: industry || undefined,
      message,
      captchaId: captchaQuery.data.id,
      captchaAnswer: parsedAnswer,
    });
  };

  const refreshCaptcha = () => {
    captchaQuery.refetch();
    setCaptchaAnswer("");
  };

  return (
    <Layout>
      <SEOHead
        title="Contact Alzar FZE | Get a Quote for Refractories, Loaders & More"
        description="Contact Alzar FZE for refractories, loaders, ceramic raw materials, cement grinding aids, and aluminum extrusion lubricants. Visit our office in Jebel Ali Free Zone, Dubai or call +971-4-8814928."
        canonical="https://www.alzarfze.com/contact"
        keywords="contact Alzar FZE Dubai, refractories inquiry UAE, loaders quote Dubai, ceramic raw materials order, cement grinding aid inquiry, glass furnace equipment quote, aluminum lubricants supplier contact, Jebel Ali Free Zone office, industrial solutions inquiry GCC"
        breadcrumbs={[
          { name: "Home", url: "https://www.alzarfze.com" },
          { name: "Contact", url: "https://www.alzarfze.com/contact" },
        ]}
      />

      {/* Hero */}
      <section className="relative py-20 lg:py-28 overflow-hidden">
        <div className="absolute inset-0">
          <img src={HERO_IMG} alt="" className="w-full h-full object-cover" />
          <div className="absolute inset-0 bg-gradient-to-r from-navy/95 via-navy/85 to-navy/70" />
        </div>
        <div className="container relative z-10">
          <h1 className="font-heading font-bold text-3xl lg:text-5xl text-white leading-tight mb-4">
            {t("contact.title")}
          </h1>
          <p className="text-lg text-white/70 leading-relaxed max-w-2xl">
            {t("contact.subtitle")}
          </p>
        </div>
      </section>

      {/* Contact Grid */}
      <section className="py-16 lg:py-24">
        <div className="container">
          <div className="grid lg:grid-cols-5 gap-12 lg:gap-16">
            {/* Form */}
            <div className="lg:col-span-3">
              <h2 className="font-heading font-bold text-2xl text-navy mb-6">{t("contact.sendUsMessage")}</h2>

              {submitted ? (
                <div className="bg-teal/5 border border-teal/20 rounded-xl p-8 text-center">
                  <CheckCircle2 className="w-12 h-12 text-teal mx-auto mb-4" />
                  <h3 className="font-heading font-semibold text-xl text-navy mb-2">{t("contact.thankYou")}</h3>
                  <p className="text-slate-dark/70 mb-4">{t("contact.thankYouDesc")}</p>
                  <div className="flex flex-wrap justify-center gap-4">
                    <a href="mailto:info@alzarfze.com" className="inline-flex items-center gap-2 bg-teal text-white px-5 py-2.5 rounded-md font-medium hover:bg-teal-dark transition-colors">
                      <Mail className="w-4 h-4" /> {t("contact.emailDirectly")}
                    </a>
                    <a href="https://wa.me/971553288217" target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 bg-green-600 text-white px-5 py-2.5 rounded-md font-medium hover:bg-green-700 transition-colors">
                      <MessageCircle className="w-4 h-4" /> {lang === "ar" ? "واتساب" : "WhatsApp"}
                    </a>
                  </div>
                  <button onClick={() => { setSubmitted(false); refreshCaptcha(); }} className="mt-4 text-sm text-teal hover:underline">{t("contact.sendAnother")}</button>
                </div>
              ) : (
                <form onSubmit={handleSubmit} className="space-y-5">
                  <div className="grid sm:grid-cols-2 gap-5">
                    <div>
                      <label htmlFor="name" className="block text-sm font-medium text-navy mb-1.5">{t("contact.name")} *</label>
                      <input
                        type="text" id="name" name="name" required
                        disabled={submitMutation.isPending}
                        className="w-full px-4 py-3 bg-white border border-navy/10 rounded-lg text-navy placeholder:text-navy/30 focus:outline-none focus:ring-2 focus:ring-teal/30 focus:border-teal transition-colors disabled:opacity-50"
                        placeholder={t("contact.placeholderName")}
                      />
                    </div>
                    <div>
                      <label htmlFor="email" className="block text-sm font-medium text-navy mb-1.5">{t("contact.email")} *</label>
                      <input
                        type="email" id="email" name="email" required
                        disabled={submitMutation.isPending}
                        className="w-full px-4 py-3 bg-white border border-navy/10 rounded-lg text-navy placeholder:text-navy/30 focus:outline-none focus:ring-2 focus:ring-teal/30 focus:border-teal transition-colors disabled:opacity-50"
                        placeholder={t("contact.placeholderEmail")}
                      />
                    </div>
                  </div>
                  <div className="grid sm:grid-cols-2 gap-5">
                    <div>
                      <label htmlFor="company" className="block text-sm font-medium text-navy mb-1.5">{t("contact.company")}</label>
                      <input
                        type="text" id="company" name="company"
                        disabled={submitMutation.isPending}
                        className="w-full px-4 py-3 bg-white border border-navy/10 rounded-lg text-navy placeholder:text-navy/30 focus:outline-none focus:ring-2 focus:ring-teal/30 focus:border-teal transition-colors disabled:opacity-50"
                        placeholder={t("contact.placeholderCompany")}
                      />
                    </div>
                    <div>
                      <label htmlFor="industry" className="block text-sm font-medium text-navy mb-1.5">{t("contact.industry")}</label>
                      <select
                        id="industry" name="industry"
                        disabled={submitMutation.isPending}
                        className="w-full px-4 py-3 bg-white border border-navy/10 rounded-lg text-navy focus:outline-none focus:ring-2 focus:ring-teal/30 focus:border-teal transition-colors disabled:opacity-50"
                      >
                        <option value="">{t("contact.selectIndustry")}</option>
                        {industries.map((ind) => (
                          <option key={ind.value} value={ind.label}>{ind.label}</option>
                        ))}
                      </select>
                    </div>
                  </div>
                  <div>
                    <label htmlFor="message" className="block text-sm font-medium text-navy mb-1.5">{t("contact.message")} *</label>
                    <textarea
                      id="message" name="message" required rows={5}
                      disabled={submitMutation.isPending}
                      className="w-full px-4 py-3 bg-white border border-navy/10 rounded-lg text-navy placeholder:text-navy/30 focus:outline-none focus:ring-2 focus:ring-teal/30 focus:border-teal transition-colors resize-none disabled:opacity-50"
                      placeholder={t("contact.placeholderMessage")}
                    />
                  </div>

                  {/* CAPTCHA */}
                  <div className="bg-navy/[0.02] border border-navy/10 rounded-lg p-4">
                    <div className="flex items-center gap-2 mb-3">
                      <ShieldCheck className="w-4 h-4 text-teal" />
                      <span className="text-sm font-medium text-navy">{t("contact.securityVerification")} *</span>
                    </div>
                    <div className="flex items-center gap-3">
                      <div className="bg-navy/5 rounded-md px-4 py-2.5 font-mono text-lg font-bold text-navy tracking-wider select-none">
                        {captchaQuery.isLoading ? "..." : captchaQuery.data?.question ?? "Error"}
                      </div>
                      <button
                        type="button"
                        onClick={refreshCaptcha}
                        disabled={captchaQuery.isFetching}
                        className="p-2 text-navy/40 hover:text-teal transition-colors rounded-md hover:bg-teal/5 disabled:opacity-50"
                        title={lang === "ar" ? "تحديث التحقق" : "Refresh CAPTCHA"}
                      >
                        <RefreshCw className={`w-4 h-4 ${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-24 px-3 py-2.5 bg-white border border-navy/10 rounded-lg text-navy text-center font-mono text-lg 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="inline-flex items-center gap-2 bg-teal hover:bg-teal-dark text-white font-semibold px-8 py-3.5 rounded-md transition-all hover:shadow-lg hover:shadow-teal/20 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {submitMutation.isPending ? (
                      <>
                        <Loader2 className="w-4 h-4 animate-spin" />
                        {t("contact.sending")}
                      </>
                    ) : (
                      <>
                        <Send className="w-4 h-4" />
                        {t("contact.send")}
                      </>
                    )}
                  </button>
                </form>
              )}
            </div>

            {/* Contact Info */}
            <div className="lg:col-span-2">
              <h2 className="font-heading font-bold text-2xl text-navy mb-6">{t("contact.contactInfo")}</h2>
              <div className="space-y-5">
                {contactInfo.map((info, i) => (
                  <div key={i} className="flex items-start gap-4">
                    <div className="p-2.5 bg-teal/10 rounded-lg shrink-0">
                      <info.icon className="w-5 h-5 text-teal" />
                    </div>
                    <div>
                      <div className="text-xs text-navy/50 font-medium uppercase tracking-wider mb-0.5">{info.label}</div>
                      {info.href ? (
                        <a href={info.href} target={info.href.startsWith("http") ? "_blank" : undefined} rel={info.href.startsWith("http") ? "noopener noreferrer" : undefined} className="text-navy hover:text-teal transition-colors font-medium" dir={(info as any).ltr ? 'ltr' : undefined}>
                          {info.value}
                        </a>
                      ) : (
                        <span className="text-navy font-medium" dir={(info as any).ltr ? 'ltr' : undefined}>{info.value}</span>
                      )}
                    </div>
                  </div>
                ))}
              </div>

              {/* WhatsApp CTA */}
              <div className="mt-8 bg-green-50 border border-green-200 rounded-xl p-6">
                <h3 className="font-heading font-semibold text-navy mb-2">{t("contact.quickWhatsapp")}</h3>
                <p className="text-sm text-slate-dark/70 mb-4">{t("contact.quickWhatsappDesc")}</p>
                <a
                  href="https://wa.me/971553288217"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center gap-2 bg-green-600 text-white px-5 py-2.5 rounded-md font-medium hover:bg-green-700 transition-colors"
                >
                  <MessageCircle className="w-4 h-4" />
                  {t("contact.whatsapp")}
                </a>
              </div>

              {/* Social Media */}
              <div className="mt-6">
                <h3 className="font-heading font-semibold text-navy mb-3">{lang === "ar" ? "تابعنا" : "Follow Us"}</h3>
                <div className="flex items-center gap-3">
                  <a
                    href="https://www.linkedin.com/company/alzar-fze/about/"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-10 h-10 rounded-lg bg-navy/5 hover:bg-teal hover:text-white text-navy flex items-center justify-center transition-colors"
                    aria-label="LinkedIn"
                  >
                    <Linkedin className="w-5 h-5" />
                  </a>
                  <a
                    href="https://www.instagram.com/alzar.fze/"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-10 h-10 rounded-lg bg-navy/5 hover:bg-teal hover:text-white text-navy flex items-center justify-center transition-colors"
                    aria-label="Instagram"
                  >
                    <Instagram className="w-5 h-5" />
                  </a>
                  <a
                    href="https://www.facebook.com/p/Alzar-FZE-100084325740456/"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-10 h-10 rounded-lg bg-navy/5 hover:bg-teal hover:text-white text-navy flex items-center justify-center transition-colors"
                    aria-label="Facebook"
                  >
                    <Facebook className="w-5 h-5" />
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Map */}
      <section className="py-16 lg:py-24 bg-warm-white">
        <div className="container">
          <h2 className="font-heading font-bold text-2xl text-navy mb-6 text-center">{t("contact.ourLocation")}</h2>
          <div className="bg-white rounded-xl border border-navy/5 shadow-sm overflow-hidden">
            <iframe
              src="https://www.google.com/maps/embed?pb=!1m17!1m12!1m3!1d1808.5!2d55.08868066137356!3d24.990300519585478!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m2!1m1!2zMjTCsDU5JzI1LjEiTiA1NcKwMDUnMTkuMyJF!5e0!3m2!1sen!2sae!4v1700000000000!5m2!1sen!2sae"
              width="100%"
              height="400"
              style={{ border: 0 }}
              allowFullScreen
              loading="lazy"
              referrerPolicy="no-referrer-when-downgrade"
              title="Alzar FZE Location - Jebel Ali Free Zone, Dubai"
            />
          </div>
          <p className="text-center text-sm text-slate-dark/50 mt-4">
            {lang === "ar" ? "LOB #21، الدوار السادس، ميناء جبل علي، المنطقة الحرة لجبل علي، دبي، الإمارات" : "LOB #21, 6th Roundabout, Mina Jebel Ali, Jebel Ali Free Zone, Dubai, UAE"}
          </p>
        </div>
      </section>
    </Layout>
  );
}
