/*
  DESIGN: "Global Nexus" — Contact section with form and info cards
  Clean layout with map placeholder and direct contact details
*/
import { Mail, Phone, MapPin, Clock, MessageCircle, Loader2, ShieldCheck, RefreshCw } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { trpc } from "@/lib/trpc";
import { useLanguage } from "@/contexts/LanguageContext";
import { trackContactFormSubmission, trackPhoneClick, trackWhatsAppClick } from "@/lib/analytics";

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

  const contactInfo = [
    {
      icon: Mail,
      title: t("contact.emailUs"),
      primary: "info@alzarfze.com",
      secondary: t("contact.weRespond"),
      href: "mailto:info@alzarfze.com",
    },
    {
      icon: Phone,
      title: t("contact.callUs"),
      primary: "+971 4 881 4928-9",
      secondary: lang === "ar" ? "فاكس: +971 4 887 3928" : "Fax: +971 4 887 3928",
      href: "tel:+97148814928",
    },
    {
      icon: MapPin,
      title: t("contact.visitUs"),
      primary: lang === "ar" ? "LOB #21، الدوار السادس" : "LOB #21, 6th Roundabout",
      secondary: lang === "ar" ? "ميناء جبل علي، المنطقة الحرة لجبل علي، دبي، الإمارات" : "Mina Jebel Ali, Jebel Ali Free Zone, Dubai, UAE",
      href: "https://maps.google.com/?q=Alzar+FZE+Jebel+Ali+Dubai",
    },
    {
      icon: Clock,
      title: t("contact.workingHours"),
      primary: t("contact.monFri"),
      secondary: t("contact.satSunClosed"),
      href: undefined,
    },
  ];

  const industries = [
    { value: "Ceramics", label: lang === "ar" ? "السيراميك" : "Ceramics" },
    { value: "Glass & Aluminum", label: lang === "ar" ? "الزجاج والألمنيوم" : "Glass & Aluminum" },
    { value: "Machinery", label: lang === "ar" ? "الآلات" : "Machinery" },
    { value: "Cement Industry", label: lang === "ar" ? "صناعة الأسمنت" : "Cement Industry" },
    { 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);
      setFormData({ name: "", email: "", company: "", industry: "", message: "" });
      setCaptchaAnswer("");
      trackContactFormSubmission("homepage", formData.industry || "general");
      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) => {
    e.preventDefault();

    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: formData.name,
      email: formData.email,
      company: formData.company || undefined,
      industry: formData.industry || undefined,
      message: formData.message,
      captchaId: captchaQuery.data.id,
      captchaAnswer: parsedAnswer,
    });
  };

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

  return (
    <section id="contact" className="py-20 lg:py-28 bg-warm-white">
      <div className="container">
        {/* Section header */}
        <div className="text-center max-w-2xl mx-auto mb-16">
          <div className="inline-flex items-center gap-2 bg-teal/10 text-teal-dark rounded-full px-4 py-1.5 mb-4">
            <span className="text-sm font-semibold tracking-wide uppercase">{t("nav.getInTouch")}</span>
          </div>
          <h2 className="font-heading font-bold text-3xl lg:text-4xl text-navy mb-4">
            {t("contact.title")}
          </h2>
          <p className="text-slate-dark/70 leading-relaxed">
            {t("contact.subtitle")}
          </p>
        </div>

        <div className="grid lg:grid-cols-5 gap-12">
          {/* Contact info cards */}
          <div className="lg:col-span-2 space-y-4">
            {contactInfo.map((info, i) => {
              const Wrapper = info.href ? "a" : "div";
              return (
                <Wrapper
                  key={i}
                  {...(info.href ? { href: info.href, target: info.href.startsWith("http") ? "_blank" : undefined, rel: info.href.startsWith("http") ? "noopener noreferrer" : undefined } : {})}
                  className="flex items-start gap-4 p-4 bg-white rounded-lg border border-navy/5 hover:border-teal/30 hover:shadow-md hover:shadow-teal/5 transition-all duration-200 group block"
                >
                  <div className="p-2.5 bg-teal/10 rounded-lg shrink-0 group-hover:bg-teal/20 transition-colors">
                    <info.icon className="w-5 h-5 text-teal" />
                  </div>
                  <div>
                    <h3 className="font-heading font-semibold text-navy text-sm mb-0.5">{info.title}</h3>
                    <p className="text-navy/80 font-medium" dir={info.href?.startsWith('mailto:') || info.href?.startsWith('tel:') ? 'ltr' : undefined}>{info.primary}</p>
                    <p className="text-sm text-slate-dark/50 mt-0.5" dir={info.href?.startsWith('tel:') ? 'ltr' : undefined}>{info.secondary}</p>
                  </div>
                </Wrapper>
              );
            })}

            {/* WhatsApp CTA */}
            <a
              href="https://wa.me/971553288217"
              target="_blank"
              rel="noopener noreferrer"
              onClick={() => trackWhatsAppClick()}
              className="flex items-center justify-center gap-3 bg-[#25D366] hover:bg-[#20BD5A] text-white font-semibold py-3.5 px-6 rounded-lg transition-colors w-full"
            >
              <MessageCircle className="w-5 h-5" />
              {t("contact.whatsapp")}
            </a>
          </div>

          {/* Contact form */}
          <div className="lg:col-span-3">
            {submitted ? (
              <div className="bg-white rounded-xl p-6 lg:p-8 shadow-lg shadow-navy/5 border border-navy/5 text-center">
                <div className="w-16 h-16 bg-teal/10 rounded-full flex items-center justify-center mx-auto mb-4">
                  <Mail className="w-8 h-8 text-teal" />
                </div>
                <h3 className="font-heading font-semibold text-xl text-navy mb-2">{t("contact.messageSent")}</h3>
                <p className="text-slate-dark/70 mb-6">{t("contact.thankYouDescShort")}</p>
                <button
                  onClick={() => { setSubmitted(false); refreshCaptcha(); }}
                  className="text-teal hover:text-teal-dark font-medium transition-colors"
                >
                  {t("contact.sendAnother")}
                </button>
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="bg-white rounded-xl p-6 lg:p-8 shadow-lg shadow-navy/5 border border-navy/5">
                <h3 className="font-heading font-semibold text-xl text-navy mb-6">{t("contact.sendUsMessage")}</h3>

                <div className="grid sm:grid-cols-2 gap-4 mb-4">
                  <div>
                    <label htmlFor="home-name" className="block text-sm font-medium text-navy/70 mb-1.5">{t("contact.name")} *</label>
                    <input
                      id="home-name"
                      type="text"
                      required
                      disabled={submitMutation.isPending}
                      value={formData.name}
                      onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                      className="w-full px-4 py-2.5 rounded-md border border-navy/15 bg-warm-white focus:border-teal focus:ring-2 focus:ring-teal/20 outline-none transition-all text-navy disabled:opacity-50"
                      placeholder={t("contact.placeholderName")}
                    />
                  </div>
                  <div>
                    <label htmlFor="home-email" className="block text-sm font-medium text-navy/70 mb-1.5">{t("contact.email")} *</label>
                    <input
                      id="home-email"
                      type="email"
                      required
                      disabled={submitMutation.isPending}
                      value={formData.email}
                      onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                      className="w-full px-4 py-2.5 rounded-md border border-navy/15 bg-warm-white focus:border-teal focus:ring-2 focus:ring-teal/20 outline-none transition-all text-navy disabled:opacity-50"
                      placeholder={t("contact.placeholderEmail")}
                    />
                  </div>
                </div>

                <div className="grid sm:grid-cols-2 gap-4 mb-4">
                  <div>
                    <label htmlFor="home-company" className="block text-sm font-medium text-navy/70 mb-1.5">{t("contact.company")}</label>
                    <input
                      id="home-company"
                      type="text"
                      disabled={submitMutation.isPending}
                      value={formData.company}
                      onChange={(e) => setFormData({ ...formData, company: e.target.value })}
                      className="w-full px-4 py-2.5 rounded-md border border-navy/15 bg-warm-white focus:border-teal focus:ring-2 focus:ring-teal/20 outline-none transition-all text-navy disabled:opacity-50"
                      placeholder={t("contact.placeholderCompany")}
                    />
                  </div>
                  <div>
                    <label htmlFor="home-industry" className="block text-sm font-medium text-navy/70 mb-1.5">{t("contact.industryOfInterest")}</label>
                    <select
                      id="home-industry"
                      disabled={submitMutation.isPending}
                      value={formData.industry}
                      onChange={(e) => setFormData({ ...formData, industry: e.target.value })}
                      className="w-full px-4 py-2.5 rounded-md border border-navy/15 bg-warm-white focus:border-teal focus:ring-2 focus:ring-teal/20 outline-none transition-all text-navy disabled:opacity-50"
                    >
                      <option value="">{t("contact.selectIndustryLower")}</option>
                      {industries.map((ind) => (
                        <option key={ind.value} value={ind.value}>{ind.label}</option>
                      ))}
                    </select>
                  </div>
                </div>

                <div className="mb-4">
                  <label htmlFor="home-message" className="block text-sm font-medium text-navy/70 mb-1.5">{t("contact.message")} *</label>
                  <textarea
                    id="home-message"
                    required
                    rows={5}
                    disabled={submitMutation.isPending}
                    value={formData.message}
                    onChange={(e) => setFormData({ ...formData, message: e.target.value })}
                    className="w-full px-4 py-2.5 rounded-md border border-navy/15 bg-warm-white focus:border-teal focus:ring-2 focus:ring-teal/20 outline-none transition-all text-navy 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 mb-6">
                  <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="w-full bg-teal hover:bg-teal-dark text-white font-semibold py-3 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"
                >
                  {submitMutation.isPending ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin" />
                      {t("contact.sending")}
                    </>
                  ) : (
                    t("contact.send")
                  )}
                </button>
                <p className="text-xs text-slate-dark/40 mt-3 text-center">
                  {t("contact.formNote")}
                </p>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
