"use client";

import { useEffect, useRef, useState, type FormEvent } from "react";
import Link from "next/link";
import { SectionIcon } from "./icons";
import type { ContactGridData } from "./ContactGrid.schema";

function chunk<T>(arr: T[], size: number): T[][] {
  const out: T[][] = [];
  for (let i = 0; i < arr.length; i += size) {
    out.push(arr.slice(i, i + size));
  }
  return out;
}

const PEOPLE_MAP: Record<string, number> = {
  "1": 1,
  "2-4": 4,
  "5-10": 8,
  "11-20": 15,
  "20+": 25,
};

const DATE_MAP_AR: Record<string, string> = {
  "this-month": "هذا الشهر",
  "next-month": "الشهر القادم",
  "3-months": "خلال ٣ أشهر",
  "6-months": "خلال ٦ أشهر",
  flexible: "متى ما يناسبكم — اقترحوا عليّ",
};
const DATE_MAP_EN: Record<string, string> = {
  "this-month": "This month",
  "next-month": "Next month",
  "3-months": "Within 3 months",
  "6-months": "Within 6 months",
  flexible: "Whenever works — please suggest",
};

function dateMapFor(): Record<string, string> {
  if (typeof document === "undefined") return DATE_MAP_AR;
  return document.documentElement.lang === "en" ? DATE_MAP_EN : DATE_MAP_AR;
}

function flash(el: HTMLElement | null) {
  if (!el) return;
  el.classList.add("is-prefilled");
  setTimeout(() => el.classList.remove("is-prefilled"), 2600);
}

export function ContactGrid({ data }: { data: ContactGridData }) {
  const { form, methods } = data;
  const [submitted, setSubmitted] = useState(false);
  const [forwardArrow, setForwardArrow] = useState<"arrow-left" | "arrow-right">("arrow-left");
  const formRef = useRef<HTMLFormElement>(null);

  useEffect(() => {
    setForwardArrow(document.documentElement.lang === "en" ? "arrow-right" : "arrow-left");
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const params = new URLSearchParams(window.location.search);
    if ([...params.keys()].length === 0) return;
    if (!formRef.current) return;

    const service = params.get("service");
    const people = params.get("people");
    const date = params.get("date");

    if (service) {
      const sel = formRef.current.querySelector<HTMLSelectElement>('select[name="service"]');
      if (sel && [...sel.options].some((o) => o.value === service)) {
        sel.value = service;
        flash(sel);
      }
    }
    if (people && PEOPLE_MAP[people] != null) {
      const inp = formRef.current.querySelector<HTMLInputElement>('input[name="people"]');
      if (inp) {
        inp.value = String(PEOPLE_MAP[people]);
        flash(inp);
      }
    }
    const dateMap = dateMapFor();
    if (date && dateMap[date]) {
      const inp = formRef.current.querySelector<HTMLInputElement>('input[name="date"]');
      if (inp) {
        inp.value = dateMap[date];
        flash(inp);
      }
    }

    requestAnimationFrame(() => {
      const target = document.getElementById("contact-form");
      if (!target) return;
      const top = target.getBoundingClientRect().top + window.pageYOffset - 80;
      window.scrollTo({ top, behavior: "smooth" });
    });

    if (window.history.replaceState) {
      window.history.replaceState({}, "", window.location.pathname + window.location.hash);
    }
  }, []);

  const onSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setSubmitted(true);
  };

  return (
    <section className="sec" id="contact-form" data-screen-label="Form and Methods" style={{ paddingTop: 48 }}>
      <div className="wrap">
        <div className="contact-grid">
          {/* FORM */}
          <div className="form-card">
            <div className="head">
              {form.eyebrow ? (
                <span className="eyebrow">
                  <span className="pip" />
                  {form.eyebrow}
                </span>
              ) : null}
              {form.title ? <h2>{form.title}</h2> : null}
              {form.subtitle ? <p>{form.subtitle}</p> : null}
            </div>
            <form ref={formRef} onSubmit={onSubmit}>
              {chunk(form.fields, 2).map((row, rowIndex) => (
                <div key={rowIndex} className={row.length === 2 ? "field-row" : ""}>
                  {row.map((field) => (
                    <label key={field.key} className="field">
                      <span>
                        {field.required ? <span className="req">*</span> : null}
                        {field.label}
                      </span>
                      {field.type === "textarea" ? (
                        <textarea
                          name={field.key}
                          placeholder={field.placeholder}
                          required={field.required}
                        />
                      ) : field.type === "select" ? (
                        <select name={field.key} defaultValue="" required={field.required}>
                          <option value="" disabled>
                            {field.placeholder}
                          </option>
                          {(field.options ?? []).map((opt) => (
                            <option key={opt.value} value={opt.value}>
                              {opt.label}
                            </option>
                          ))}
                        </select>
                      ) : (
                        <input
                          type={field.type}
                          name={field.key}
                          placeholder={field.placeholder}
                          required={field.required}
                        />
                      )}
                    </label>
                  ))}
                </div>
              ))}
              <div className="field-actions">
                <button
                  type="submit"
                  className="submit"
                  style={submitted ? { background: "var(--green-600)" } : undefined}
                >
                  {submitted ? form.success_message : form.submit_label}{" "}
                  {submitted ? null : <SectionIcon name={forwardArrow} size={16} />}
                </button>
                {form.whatsapp_alt_label ? (
                  <a
                    href={form.whatsapp_alt_href}
                    className="wa-alt"
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    <SectionIcon name="message-circle" size={16} />
                    {form.whatsapp_alt_label}
                  </a>
                ) : null}
              </div>
            </form>
          </div>

          {/* METHODS */}
          <div>
            {methods.eyebrow ? (
              <span className="eyebrow">
                <span className="pip" />
                {methods.eyebrow}
              </span>
            ) : null}
            {methods.title_lines.length > 0 ? (
              <h2 className="h-section" style={{ fontSize: 32, margin: "8px 0 20px" }}>
                {methods.title_lines.map((line, i) => (
                  <span
                    key={i}
                    dangerouslySetInnerHTML={{
                      __html: line + (i < methods.title_lines.length - 1 ? "<br/>" : ""),
                    }}
                  />
                ))}
              </h2>
            ) : null}
            <div className="methods">
              {methods.items.map((method, i) => {
                const className =
                  method.tone === "default" ? "method" : `method ${method.tone}`;
                const isExternal = method.href.startsWith("http");
                const isInternal =
                  method.href.startsWith("/") && !method.href.startsWith("//");
                const inner = (
                  <>
                    <span className="ic">
                      <SectionIcon name={method.icon} size={20} />
                    </span>
                    <div>
                      <div className="ttl">{method.title}</div>
                      <div
                        className="v"
                        style={
                          method.icon === "map-pin"
                            ? { direction: "rtl", textAlign: "right" }
                            : undefined
                        }
                      >
                        {method.value}
                      </div>
                    </div>
                  </>
                );
                if (isInternal) {
                  return (
                    <Link key={i} className={className} href={method.href}>
                      {inner}
                    </Link>
                  );
                }
                return (
                  <a
                    key={i}
                    className={className}
                    href={method.href}
                    target={isExternal ? "_blank" : undefined}
                    rel={isExternal ? "noopener noreferrer" : undefined}
                  >
                    {inner}
                  </a>
                );
              })}
            </div>
            {methods.info_card && (methods.info_card.title || methods.info_card.body) ? (
              <div className="info-card">
                {methods.info_card.title ? <h3>{methods.info_card.title}</h3> : null}
                {methods.info_card.body ? <p>{methods.info_card.body}</p> : null}
              </div>
            ) : null}
          </div>
        </div>
      </div>
    </section>
  );
}
