"use client";

import { useEffect, useRef, useState } from "react";

interface DropdownOption {
  value: string;
  label: string;
  meta: string;
  icon: React.ReactNode;
}

interface DropdownField {
  name: "service" | "people" | "date";
  fieldLabel: string;
  placeholder: string;
  ariaLabel: string;
  options: ReadonlyArray<DropdownOption>;
}

const ChevronDown = () => (
  <svg
    className="chev"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth={2.2}
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <polyline points="6 9 12 15 18 9" />
  </svg>
);

const Ic = ({ children }: { children: React.ReactNode }) => (
  <svg
    className="ic"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth={1.8}
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    {children}
  </svg>
);

const SERVICE_OPTIONS: DropdownOption[] = [
  { value: "events", label: "فعالية", meta: "حفلات وأمسيات وتنظيم خاص", icon: <Ic><path d="M12 3l1.9 5.8L20 10l-4.5 4 1.4 6L12 17.3 7.1 20l1.4-6L4 10l6.1-1.2z" /></Ic> },
  { value: "religious", label: "رحلة دينية", meta: "زيارات ورحلات بروح مطمئنة", icon: <Ic><path d="M12 21a8 8 0 0 0 8-8c0-4-4-9-8-12-4 3-8 8-8 12a8 8 0 0 0 8 8z" /></Ic> },
  { value: "umrah", label: "عمرة", meta: "برامج كاملة من البداية للنهاية", icon: <Ic><path d="M3 21h18M5 21V10l7-5 7 5v11M10 21v-6h4v6" /></Ic> },
  { value: "tourism", label: "سياحة", meta: "وجهات وبرامج داخل المملكة", icon: <Ic><><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 1 1 18 0z" /><circle cx="12" cy="10" r="3" /></></Ic> },
  { value: "general", label: "استفسار عام", meta: "معلومات أو تخصيص لاحقاً", icon: <Ic><><circle cx="12" cy="12" r="9" /><path d="M9.5 9a2.5 2.5 0 0 1 5 0c0 2-2.5 2.5-2.5 4M12 17.5h.01" /></></Ic> },
];

const PEOPLE_OPTIONS: DropdownOption[] = [
  { value: "1", label: "١ شخص", meta: "رحلة فردية", icon: <Ic><><circle cx="12" cy="8" r="4" /><path d="M4 21a8 8 0 0 1 16 0" /></></Ic> },
  { value: "2-4", label: "٢ — ٤ أشخاص", meta: "عائلة صغيرة", icon: <Ic><><circle cx="9" cy="8" r="4" /><circle cx="17" cy="10" r="3" /><path d="M2 21a7 7 0 0 1 14 0M14 21a5 5 0 0 1 8 0" /></></Ic> },
  { value: "5-10", label: "٥ — ١٠ أشخاص", meta: "مجموعة أصدقاء", icon: <Ic><><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" /><circle cx="9" cy="7" r="4" /><path d="M22 21v-2a4 4 0 0 0-3-3.87" /><path d="M15 3a4 4 0 0 1 0 7.75" /></></Ic> },
  { value: "11-20", label: "١١ — ٢٠ شخص", meta: "رحلة جماعية", icon: <Ic><><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" /><circle cx="9" cy="7" r="4" /><path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3a4 4 0 0 1 0 7.75" /></></Ic> },
  { value: "20+", label: "أكثر من ٢٠ شخص", meta: "مجموعة كبيرة / شركة", icon: <Ic><><circle cx="9" cy="7" r="3" /><circle cx="15" cy="9" r="2.5" /><circle cx="5" cy="11" r="2" /><circle cx="19" cy="11" r="2" /><path d="M2 21a7 7 0 0 1 14 0M14 21a6 6 0 0 1 8 0" /></></Ic> },
];

const DATE_OPTIONS: DropdownOption[] = [
  { value: "this-month", label: "هذا الشهر", meta: "رحلة سريعة في الأيام القادمة", icon: <Ic><><rect x="3" y="4" width="18" height="18" rx="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" /><circle cx="12" cy="16" r="1.5" /></></Ic> },
  { value: "next-month", label: "الشهر القادم", meta: "٣٠ يوماً للتخطيط", icon: <Ic><><rect x="3" y="4" width="18" height="18" rx="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" /><path d="M9 15l2 2 4-4" /></></Ic> },
  { value: "3-months", label: "خلال ٣ أشهر", meta: "برنامج كامل بترتيب مريح", icon: <Ic><><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" /></></Ic> },
  { value: "6-months", label: "خلال ٦ أشهر", meta: "للرحلات الكبيرة", icon: <Ic><><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2M3.5 9a9 9 0 0 1 1.5-3" /></></Ic> },
  { value: "flexible", label: "متى ما يناسبكم", meta: "سنقترح أفضل موعد", icon: <Ic><path d="M3 12a9 9 0 0 1 15-6.7L21 8M21 3v5h-5M21 12a9 9 0 0 1-15 6.7L3 16M3 21v-5h5" /></Ic> },
];

const FIELDS: DropdownField[] = [
  { name: "service", fieldLabel: "نوع الخدمة", placeholder: "اختر الخدمة المناسبة", ariaLabel: "نوع الخدمة", options: SERVICE_OPTIONS },
  { name: "people", fieldLabel: "عدد الأشخاص", placeholder: "٢ — ١٠ أشخاص", ariaLabel: "عدد الأشخاص", options: PEOPLE_OPTIONS },
  { name: "date", fieldLabel: "التاريخ المتوقع", placeholder: "حدّد الفترة", ariaLabel: "التاريخ المتوقع", options: DATE_OPTIONS },
];

type Selections = Record<DropdownField["name"], DropdownOption | null>;

export function HeroStrip() {
  const [openField, setOpenField] = useState<DropdownField["name"] | null>(null);
  const [selections, setSelections] = useState<Selections>({ service: null, people: null, date: null });
  const formRef = useRef<HTMLFormElement>(null);

  useEffect(() => {
    if (openField === null) return;
    const onClick = (event: MouseEvent) => {
      const target = event.target as HTMLElement | null;
      if (!target?.closest(".hero-strip .seg")) setOpenField(null);
    };
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") setOpenField(null);
    };
    document.addEventListener("click", onClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("click", onClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [openField]);

  const handleToggle = (name: DropdownField["name"]) => {
    setOpenField((current) => (current === name ? null : name));
  };

  const handleSelect = (name: DropdownField["name"], option: DropdownOption) => {
    setSelections((prev) => ({ ...prev, [name]: option }));
    setOpenField(null);
  };

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    if (!formRef.current) return;
    (Object.keys(selections) as Array<DropdownField["name"]>).forEach((name) => {
      const input = formRef.current?.elements.namedItem(name);
      if (input instanceof HTMLInputElement && !input.value) {
        input.disabled = true;
        // Re-enable after submit so unmounting doesn't break the form.
        setTimeout(() => (input.disabled = false), 0);
      }
    });
    // Let the native GET submit proceed.
    void event;
  };

  return (
    <div className="hero-strip-wrap">
      <form
        ref={formRef}
        className="hero-strip"
        id="heroForm"
        action="/contact"
        method="get"
        onSubmit={handleSubmit}
      >
        {FIELDS.map((field) => {
          const isOpen = openField === field.name;
          const selected = selections[field.name];
          const segClasses = ["seg", isOpen && "is-open", selected && "has-value"]
            .filter(Boolean)
            .join(" ");

          return (
            <div
              key={field.name}
              className={segClasses}
              data-field={field.name}
              role="button"
              tabIndex={0}
              aria-haspopup="listbox"
              aria-expanded={isOpen}
              onClick={(event) => {
                if ((event.target as HTMLElement).closest(".hero-pop")) return;
                handleToggle(field.name);
              }}
              onKeyDown={(event) => {
                if (event.key === "Enter" || event.key === " ") {
                  event.preventDefault();
                  handleToggle(field.name);
                }
              }}
            >
              <span className="lab">{field.fieldLabel}</span>
              <div className="v">
                <span className="txt">{selected?.label ?? field.placeholder}</span>
                <ChevronDown />
              </div>
              <input type="hidden" name={field.name} value={selected?.value ?? ""} />
              <div className="hero-pop" role="listbox" aria-label={field.ariaLabel}>
                {field.options.map((option) => (
                  <button
                    type="button"
                    key={option.value}
                    data-val={option.value}
                    data-label={option.label}
                    className={selected?.value === option.value ? "is-selected" : undefined}
                    onClick={(event) => {
                      event.stopPropagation();
                      handleSelect(field.name, option);
                    }}
                  >
                    {option.icon}
                    <span>
                      {option.label}
                      <span className="meta">{option.meta}</span>
                    </span>
                  </button>
                ))}
              </div>
            </div>
          );
        })}
        <button type="submit" className="go">
          اطلب برنامجك <i data-lucide="arrow-left" />
        </button>
      </form>
    </div>
  );
}
