"use client";

import { useEffect, useRef, useState } from "react";
import {
    DEFAULT_LOCALE,
    getStoredLocale,
    getStoredLocaleRaw,
    LOCALE_CHANGE_EVENT,
    type LocaleCode,
} from "@/i18n/localeSwitcher";
import staticCopy from "@/i18n/staticCopy.json";

const IconDropDown = () => (
    <svg width="15" height="9" viewBox="0 0 15 9" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M13.6641 0.748047L7.42406 6.74805L0.664063 0.748046" stroke="#053F31" strokeWidth="2" />
    </svg>

);

export default function ContactContent({ 
  addressItems = [], 
  extraItems = [] 
}: { 
  addressItems?: any[], 
  extraItems?: any[] 
}) {
  const sectionRef = useRef<HTMLElement>(null);
  const [inView, setInView] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitStatus, setSubmitStatus] = useState<{ success?: boolean; message?: string } | null>(null);
  const [uiLocale, setUiLocale] = useState<LocaleCode>(DEFAULT_LOCALE);

  const [formData, setFormData] = useState({
    name_or_company: "",
    email: "",
    phone: "",
    country: "",
    company: "",
    inquiry_type: "",
    message: "",
    privacy_accepted: false
  });

  const [inquiryTypeChoices, setInquiryTypeChoices] = useState<
    { id: string; label: string; value: string }[]
  >([]);

  useEffect(() => {
    const syncLocale = () => {
      setUiLocale(getStoredLocale());
    };

    syncLocale();
    window.addEventListener("storage", syncLocale);
    window.addEventListener(LOCALE_CHANGE_EVENT, syncLocale);
    return () => {
      window.removeEventListener("storage", syncLocale);
      window.removeEventListener(LOCALE_CHANGE_EVENT, syncLocale);
    };
  }, []);

  useEffect(() => {
    let cancelled = false;
    const base = (process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL ?? "").replace(/\/$/, "");
    if (!base) return;
    fetch(`${base}/store/form-options`, {
      method: "GET",
      headers: {
        "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
        "x-medusa-locale": (getStoredLocaleRaw() ?? getStoredLocale()).trim(),
      },
      cache: "no-store",
    })
      .then((r) => (r.ok ? r.json() : null))
      .then((json: unknown) => {
        if (cancelled || !json || typeof json !== "object") return;
        const forms = (json as Record<string, unknown>).forms;
        if (!forms || typeof forms !== "object") return;
        const block =
          (forms as Record<string, unknown>)["Contact Form"] ??
          (forms as Record<string, unknown>)["contact form"];
        if (!block || typeof block !== "object") return;
        const raw = (block as Record<string, unknown>).inquiry_type;
        if (!Array.isArray(raw)) return;
        const mapped = raw
          .map((item: unknown) => {
            const o = item as Record<string, unknown>;
            const value = String(o?.value ?? "").trim();
            if (!value) return null;
            return {
              id: String(o?.id ?? value),
              label: String(o?.label ?? value).trim() || value,
              value,
            };
          })
          .filter(Boolean) as { id: string; label: string; value: string }[];
        setInquiryTypeChoices(mapped);
      })
      .catch(() => {});
    return () => {
      cancelled = true;
    };
  }, [uiLocale]);

  useEffect(() => {
    const el = sectionRef.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      ([entry]) => setInView(!!entry.isIntersecting),
      { threshold: 0.12, rootMargin: "0px" }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { id, value, type } = e.target;
    const val = type === 'checkbox' ? (e.target as HTMLInputElement).checked : value;
    setFormData(prev => ({ ...prev, [id]: val }));
  };

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

    try {
      const res = await fetch(`${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/store/contact`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
        },
        body: JSON.stringify(formData),
      });

      if (res.ok) {
        setSubmitStatus({ success: true, message: staticCopy.contact[uiLocale].successMessage });
        setFormData({
          name_or_company: "",
          email: "",
          phone: "",
          country: "",
          company: "",
          inquiry_type: "",
          message: "",
          privacy_accepted: false
        });
      } else {
        const err = await res.json();
        setSubmitStatus({ success: false, message: err.message || staticCopy.contact[uiLocale].errorMessage });
      }
    } catch (error) {
      setSubmitStatus({ success: false, message: staticCopy.contact[uiLocale].connectionError });
    } finally {
      setIsSubmitting(false);
    }
  };

  const addressCards = addressItems.filter(item => !item.name?.toLowerCase().includes("email") && !item.email);
  const emailItem = addressItems.find(item => item.name?.toLowerCase().includes("email") || item.email);
  const emailAddress = emailItem?.email || "info@biomket.com";

  return (
    <section
      ref={sectionRef}
      className={`mb-[50px] sm:mb-12 md:mb-14 lg:mb-16 xl:mb-[70px] mx-0 md:mx-[40px] lg:mx-0 relative z-20 ${inView ? "contact-content-in" : ""}`}
    >
      <style dangerouslySetInnerHTML={{ __html: `
        .contact-content-step { opacity: 0; }
        .contact-content-in .contact-content-step {
          animation: contact-content-zoom-in 0.65s ease-out forwards;
        }
        @keyframes contact-content-zoom-in {
          from { opacity: 0; transform: scale(0.96); }
          to { opacity: 1; transform: scale(1); }
        }
      `}} />
      <div className="xl:max-w-[1240px] 2xl:max-w-[1440px] sm:mx-auto grid grid-cols-1 lg:grid-cols-12 gap-[12px] font-outfit selection:bg-[#053F31] selection:text-white contact-content-step">

        <div className="lg:col-span-4 space-y-4 ">
          {addressCards.map((item, idx) => {
            const baseType = item.base_type || item.type;
            const fullTitle = baseType ? `${item.name} (${baseType})` : item.name;
            return (
              <div key={idx} className="bg-[#DAE6DC]/70 rounded-[20px] border border-[#053F31]/10 p-[20px] mb-3">
                <h4 className="flex items-center gap-2 font-semibold text-[20px] sm:text-[22px] text-[#053F31] border-b border-[#000000]/10 pb-[15px]">
                  <img src="/map_logo_green.png" alt="map_logo" className="shrink-0" />
                  {fullTitle}
                </h4>
                <p className="text-[18px] font-light text-[#424242] leading-relaxed py-[10px] whitespace-pre-line">
                  {item.address}
                </p>
                
                <div className="flex items-center gap-2 text-[20px] font-medium text-[#053F31]">
                  <img src="/message_logo_green.png" alt="email_logo" className="shrink-0" />
                  <a href={`mailto:${emailAddress}`} className="hover:underline">{emailAddress}</a>
                </div>
              </div>
            );
          })}

          {extraItems.map((item, idx) => (
            <div key={idx} className="bg-[#F7FAF8] border border-[#053F31]/10 rounded-[20px] p-[20px] mb-3">
              <h4 className="flex items-center gap-2 font-semibold text-[20px] sm:text-[22px] text-[#053F31] border-b border-[#000000]/10 pb-[15px]">
                <div dangerouslySetInnerHTML={{ __html: item.svg }} className="w-8 h-8 flex items-center justify-center shrink-0" />
                {item.title}
              </h4>
              <p className="text-[18px] font-light text-[#424242] leading-relaxed pt-[10px]">
                {item.description}
              </p>
            </div>
          ))}
        </div>

        <div className="lg:col-span-8">
          <div className=" bg-[#F7FAF8] border border-[#053F31]/10 rounded-[20px] p-[20px] sm:p-[20px] min-w-[320px]">
            <h4  className="text-[20px] sm:text-[22px] font-semibold text-[#053F31] mb-[20px] pb-[10px] border-b border-[#000000]/10">{staticCopy.contact[uiLocale].contactForm}</h4>

            <form className="space-y-6" onSubmit={handleSubmit}>
              <div className="grid grid-cols-1 md:grid-cols-2 mb-[15px] gap-[21px]">
                <div>
                  <label htmlFor="name_or_company" className="block text-[18px] font-medium text-[#000000] mb-[8px]">{staticCopy.contact[uiLocale].nameCompanyLabel} <span className="text-[#FF0000]">*</span></label>
                  <div className="relative">
                    <input id="name_or_company" value={formData.name_or_company} onChange={handleChange} placeholder={staticCopy.contact[uiLocale].companyName} required className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-2.5 focus:outline-none focus:border-gray-300 font-light text-[18px] text-[#424242] placeholder:text-[#999999]" />
                    <div className="absolute bottom-0 left-[30px] h-[2px] w-[60px] bg-[#053F31] z-10"></div>
                  </div>
                </div>
                <div>
                  <label htmlFor="email" className="block text-[18px] font-medium text-[#000000] mb-[8px]">{staticCopy.contact[uiLocale].emailLabel} <span className="text-[#FF0000]">*</span></label>
                  <div className="relative">
                    <input id="email" type="email" value={formData.email} onChange={handleChange} placeholder={staticCopy.contact[uiLocale].email} required className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-2.5 focus:outline-none focus:border-gray-300 font-light text-[18px] text-[#424242] placeholder:text-[#999999]" />
                    <div className="absolute bottom-0 left-[30px] h-[2px] w-[60px] bg-[#053F31] z-10"></div>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 mb-[15px] gap-[21px]">
              <div>
                  <label htmlFor="phone" className="block text-[18px] font-medium text-[#000000] mb-[8px]">{staticCopy.contact[uiLocale].phoneLabel} <span className="text-[#FF0000]">*</span></label>
                  <div className="relative">
                    <input id="phone" value={formData.phone} onChange={handleChange} placeholder={staticCopy.contact[uiLocale].phone} required className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-2.5 focus:outline-none focus:border-gray-300 font-light text-[18px] text-[#424242] placeholder:text-[#999999]" />
                    <div className="absolute bottom-0 left-[30px] h-[2px] w-[60px] bg-[#053F31] z-10"></div>
                  </div>
                </div>
                <div>
                  <label htmlFor="country" className="block text-[18px] font-medium text-[#000000] mb-[8px]">{staticCopy.contact[uiLocale].countryLabel} <span className="text-[#FF0000]">*</span></label>
                  <div className="relative">
                    <input id="country" value={formData.country} onChange={handleChange} placeholder={staticCopy.contact[uiLocale].country} required className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-2.5 focus:outline-none focus:border-gray-300 font-light text-[18px] text-[#424242] placeholder:text-[#999999]" />
                    <div className="absolute bottom-0 left-[30px] h-[2px] w-[60px] bg-[#053F31] z-10"></div>
                  </div>
                </div>
              </div>

              <div className="mb-[15px]">
                <div>
                    <label htmlFor="company" className="block text-[18px] font-medium text-[#000000] mb-[8px]">{staticCopy.contact[uiLocale].companyLabel} </label>
                    <div className="relative">
                        <input id="company" value={formData.company} onChange={handleChange} placeholder={staticCopy.contact[uiLocale].company} className="w-full border border-[#053F31]/20 rounded-[5px] px-[30px] py-2.5 focus:outline-none focus:border-gray-300 font-light text-[18px] text-[#424242] placeholder:text-[#999999]" />
                        <div className="absolute bottom-0 left-[30px] h-[2px] w-[60px] bg-[#053F31] z-10"></div>
                    </div>
                </div>
              </div>

              <div className="mb-[15px]">
                <label htmlFor="inquiry_type" className="block text-[18px] font-medium text-gray-900 mb-[9px]">{staticCopy.contact[uiLocale].inquiryTypeLabel} <span className="text-[#FF0000]">*</span></label>
                <div className="relative">
                  <select id="inquiry_type" value={formData.inquiry_type} onChange={handleChange} required className="w-full border border-[#053F31]/20 rounded-[5px] px-4 py-2.5 appearance-none focus:outline-none focus:border-gray-300 font-light text-[18px] text-[#424242]">
                    <option value="" disabled>{staticCopy.contact[uiLocale].selectInquiryType}</option>
                    {inquiryTypeChoices.map((opt) => (
                      <option key={opt.id} value={opt.value}>
                        {opt.label}
                      </option>
                    ))}
                  </select>
                  <div className="absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none text-gray-400"><IconDropDown /></div>
                  <div className="absolute bottom-0 left-[30px] h-[2px] w-[60px] bg-[#053F31] z-10"></div>
                </div>
              </div>

              <div className="mb-0">
                <label htmlFor="message" className="block text-[18px] font-medium text-gray-900 mb-[9px]">{staticCopy.contact[uiLocale].messageLabel} <span className="text-[#FF0000]">*</span></label>
                <div className="relative">
                  <textarea id="message" value={formData.message} onChange={handleChange} required rows={4} placeholder={staticCopy.contact[uiLocale].message} className="w-full h-[100px] border border-[#053F31]/20 rounded-[5px] px-4 py-3 focus:outline-none focus:border-gray-300 font-light text-[18px] text-[#424242] placeholder:text-[#999999] resize-none"></textarea>
                  <div className="absolute bottom-1.5 left-[30px] h-[2px] w-[60px] bg-[#053F31] z-10"></div>
                </div>
              </div>

              <div className="flex items-center gap-[10px] py-[15px] mb-0">
                <input type="checkbox" id="privacy_accepted" checked={formData.privacy_accepted} onChange={handleChange} className="w-4 h-4 text-[#053F31] rounded border-[#053F31] focus:ring-[#053F31] cursor-pointer" required    />
                <label htmlFor="privacy_accepted" className="text-[20px] text-gray-900 p-0 font-medium cursor-pointer">{staticCopy.contact[uiLocale].privacyLabel} <span className="text-[#FF0000]">*</span></label>
              </div>

              {submitStatus && (
                <div className={`p-4 rounded-[10px] ${submitStatus.success ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                    {submitStatus.message}
                </div>
              )}

              <div>
                <button type="submit" disabled={isSubmitting} className="bg-[#053F31] cursor-pointer text-[18px] text-white font-semibold py-[7px] ps-[15px] pe-[7px] rounded-full hover:bg-emerald-800 transition disabled:opacity-50 flex items-center gap-[10px]">
                  {isSubmitting ? staticCopy.contact[uiLocale].sending : staticCopy.contact[uiLocale].sendInquiry}
                  <div className="bg-[#F7FAF8] rounded-full w-[36px] h-[36px] flex items-center justify-center shrink-0">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
                        <path d="M7 17L17 7M17 7H9M17 7V15" stroke="#053F31" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  </div>
                </button>
              </div>

            </form>
          </div>
        </div>

      </div>
    </section>
  );
}
 