"use client";

import {
  createContext,
  useContext,
  useEffect,
  useId,
  useState,
  type FormEvent,
  type ReactNode,
} from "react";
import { WHATSAPP, consentText } from "@/lib/content";

export type EnquiryIntent = "enquire" | "visit" | "brochure" | "price";

type EnquiryContextValue = {
  openEnquiry: (intent?: EnquiryIntent) => void;
};

const EnquiryContext = createContext<EnquiryContextValue>({
  openEnquiry: () => undefined,
});

export function useEnquiry() {
  return useContext(EnquiryContext);
}

const intentCopy: Record<EnquiryIntent, { title: string; lead: string }> = {
  enquire: {
    title: "Enquire Now",
    lead: "Share your details and our team will get in touch about Nirala Diadem.",
  },
  visit: {
    title: "Book a Site Visit",
    lead: "Tell us when to reach you and we will arrange a walkthrough of the project.",
  },
  brochure: {
    title: "Request the Brochure",
    lead: "Leave your contact details and we will share the project brochure with you.",
  },
  price: {
    title: "Request the Price List",
    lead: "Ask for the latest price, payment plan, and availability.",
  },
};

type Fields = {
  name: string;
  phone: string;
  email: string;
  message: string;
  consent: boolean;
};

const emptyFields: Fields = {
  name: "",
  phone: "",
  email: "",
  message: "",
  consent: true,
};

function normalizePhone(value: string) {
  const digits = value.replace(/\D/g, "");
  if (digits.length === 12 && digits.startsWith("91")) return digits.slice(2);
  if (digits.length === 11 && digits.startsWith("0")) return digits.slice(1);
  return digits;
}

function validate(values: Fields) {
  const errors: Partial<Record<keyof Fields, string>> = {};
  if (values.name.trim().length < 2) errors.name = "Please enter your name.";
  if (!/^[6-9]\d{9}$/.test(normalizePhone(values.phone))) {
    errors.phone = "Enter a valid 10-digit mobile number.";
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email.trim())) {
    errors.email = "Enter a valid email address.";
  }
  if (values.message.trim().length < 4) errors.message = "Please add a short message.";
  if (!values.consent) errors.consent = "Please authorize us to contact you.";
  return errors;
}

export function EnquiryForm({
  intent = "enquire",
  idPrefix,
  compact = false,
}: {
  intent?: EnquiryIntent;
  idPrefix?: string;
  compact?: boolean;
}) {
  const reactId = useId();
  const prefix = idPrefix ?? reactId;
  const copy = intentCopy[intent];
  const [values, setValues] = useState<Fields>(emptyFields);
  const [errors, setErrors] = useState<Partial<Record<keyof Fields, string>>>({});
  const [sent, setSent] = useState(false);

  function update<K extends keyof Fields>(key: K, value: Fields[K]) {
    setValues((current) => ({ ...current, [key]: value }));
    setErrors((current) => ({ ...current, [key]: undefined }));
  }

  function onSubmit(event: FormEvent) {
    event.preventDefault();
    const nextErrors = validate(values);
    setErrors(nextErrors);
    if (Object.keys(nextErrors).length > 0) return;

    const phone = normalizePhone(values.phone);
    const text = [
      `Enquiry: Nirala Diadem, Sector 10, Greater Noida West`,
      `Request: ${copy.title}`,
      `Name: ${values.name.trim()}`,
      `Phone: +91 ${phone}`,
      `Email: ${values.email.trim()}`,
      `Message: ${values.message.trim()}`,
    ].join("\n");

    const url = `${WHATSAPP}?text=${encodeURIComponent(text)}`;
    window.open(url, "_blank", "noopener,noreferrer");
    setSent(true);
  }

  if (sent) {
    return (
      <div className="rounded-2xl bg-white p-6 text-center shadow-xl ring-1 ring-black/5">
        <p className="text-xs font-semibold tracking-[0.22em] text-teal uppercase">Enquiry received</p>
        <h3 className="mt-2 text-2xl font-bold text-navy">Thank you, {values.name.trim().split(" ")[0]}.</h3>
        <p className="mt-3 text-sm leading-6 text-muted">
          WhatsApp is opening with your details so the sales team can reply on +91 99903 79434. If the window did not
          open, use the button below.
        </p>
        <a
          href={`${WHATSAPP}?text=${encodeURIComponent(`Hi, I am ${values.name.trim()}. I would like details on Nirala Diadem.`)}`}
          target="_blank"
          rel="noreferrer"
          className="mt-5 inline-flex rounded-full bg-teal px-5 py-3 text-sm font-semibold text-white hover:bg-teal-dark"
        >
          Open WhatsApp
        </a>
      </div>
    );
  }

  return (
    <form onSubmit={onSubmit} noValidate className="rounded-2xl bg-white p-5 shadow-xl ring-1 ring-black/5 sm:p-6">
      <p className="text-xs font-semibold tracking-[0.22em] text-teal uppercase">{copy.title}</p>
      {!compact ? <p className="mt-2 text-sm leading-6 text-muted">{copy.lead}</p> : null}
      <div className="mt-4 space-y-3">
        <Field
          id={`${prefix}-name`}
          label="Name"
          value={values.name}
          error={errors.name}
          onChange={(value) => update("name", value)}
          autoComplete="name"
        />
        <Field
          id={`${prefix}-phone`}
          label="Phone Number"
          value={values.phone}
          error={errors.phone}
          onChange={(value) => update("phone", value)}
          autoComplete="tel"
          inputMode="tel"
        />
        <Field
          id={`${prefix}-email`}
          label="Email"
          type="email"
          value={values.email}
          error={errors.email}
          onChange={(value) => update("email", value)}
          autoComplete="email"
        />
        <label className="block text-sm font-medium text-ink" htmlFor={`${prefix}-message`}>
          Message
          <textarea
            id={`${prefix}-message`}
            value={values.message}
            onChange={(event) => update("message", event.target.value)}
            rows={compact ? 3 : 4}
            placeholder="I am interested in a studio apartment."
            className="mt-1.5 w-full resize-y rounded-xl border border-line bg-cream/60 px-3.5 py-3 text-sm font-normal outline-none focus:border-teal focus:ring-2 focus:ring-teal/20"
          />
        </label>
        {errors.message ? <p className="text-xs text-orange">{errors.message}</p> : null}
        <label className="flex items-start gap-2.5 text-xs leading-5 text-muted">
          <input
            type="checkbox"
            checked={values.consent}
            onChange={(event) => update("consent", event.target.checked)}
            className="mt-0.5 size-4 accent-teal"
          />
          <span>{consentText}</span>
        </label>
        {errors.consent ? <p className="text-xs text-orange">{errors.consent}</p> : null}
        <button
          type="submit"
          className="w-full rounded-full bg-teal px-5 py-3 text-sm font-semibold tracking-wide text-white transition hover:bg-teal-dark"
        >
          Submit
        </button>
      </div>
    </form>
  );
}

function Field({
  id,
  label,
  value,
  onChange,
  error,
  type = "text",
  autoComplete,
  inputMode,
}: {
  id: string;
  label: string;
  value: string;
  onChange: (value: string) => void;
  error?: string;
  type?: string;
  autoComplete?: string;
  inputMode?: "tel" | "email" | "text";
}) {
  return (
    <label className="block text-sm font-medium text-ink" htmlFor={id}>
      {label}
      <input
        id={id}
        type={type}
        value={value}
        autoComplete={autoComplete}
        inputMode={inputMode}
        onChange={(event) => onChange(event.target.value)}
        className="mt-1.5 w-full rounded-xl border border-line bg-cream/60 px-3.5 py-3 text-sm font-normal outline-none focus:border-teal focus:ring-2 focus:ring-teal/20"
      />
      {error ? <span className="mt-1 block text-xs font-normal text-orange">{error}</span> : null}
    </label>
  );
}

export function EnquiryProvider({ children }: { children: ReactNode }) {
  const [intent, setIntent] = useState<EnquiryIntent | null>(null);

  useEffect(() => {
    if (!intent) return;
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") setIntent(null);
    };
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKey);
    };
  }, [intent]);

  return (
    <EnquiryContext.Provider value={{ openEnquiry: (next = "enquire") => setIntent(next) }}>
      {children}
      {intent ? (
        <div className="fixed inset-0 z-[80] flex items-end justify-center p-3 sm:items-center sm:p-6">
          <button
            aria-label="Close enquiry form"
            className="absolute inset-0 bg-navy/70"
            onClick={() => setIntent(null)}
          />
          <div className="relative z-10 max-h-[92vh] w-full max-w-md overflow-y-auto">
            <button
              onClick={() => setIntent(null)}
              className="absolute top-3 right-3 z-10 grid size-9 place-items-center rounded-full bg-cream text-navy"
              aria-label="Close"
            >
              ×
            </button>
            <EnquiryForm key={intent} intent={intent} idPrefix="modal" />
          </div>
        </div>
      ) : null}
    </EnquiryContext.Provider>
  );
}
