"use client";

import { useActionState, useEffect } from "react";
import { ArrowRight, LoaderCircle } from "lucide-react";

import { submitLead, type LeadFormState } from "@/app/actions";
import NumericPhoneInput from "@/components/forms/NumericPhoneInput";
import { errorAlert, successAlert } from "@/lib/alerts";
import type { Dictionary } from "@/lib/i18n";
import type { Locale } from "@/lib/locales";

const initialState: LeadFormState = {};

type LeadFormProps = {
  dictionary: Dictionary;
  locale: Locale;
  mode: "contact" | "demo";
};

const fieldClass =
  "mt-1.5 h-11 w-full rounded-lg border border-[#dde4f1] bg-white px-3 text-[13px] text-[#253052] outline-none transition placeholder:text-[#a7b0c0] focus:border-[#6b72f2] focus:ring-3 focus:ring-[#e9eaff]";

export default function LeadForm({ dictionary, locale, mode }: LeadFormProps) {
  const [state, formAction, pending] = useActionState(submitLead, initialState);
  const form = dictionary.form;

  useEffect(() => {
    if (state.success) {
      void successAlert(form.success, { locale });
    } else if (state.message) {
      void errorAlert(state.message, { locale });
    }
  }, [form.success, locale, state.message, state.success]);

  if (state.success) {
    return (
      <div className="rounded-2xl border border-emerald-100 bg-emerald-50 p-6 text-[14px] leading-7 text-emerald-800">
        {form.success}
      </div>
    );
  }

  return (
    <form action={formAction} className="rounded-2xl border border-[#e2e7f2] bg-white p-5 shadow-[0_16px_45px_rgba(40,55,105,0.08)] sm:p-7">
      <input type="hidden" name="locale" value={locale} />
      <input type="hidden" name="mode" value={mode} />
      <div className="hidden" aria-hidden="true">
        <label htmlFor="website">Website</label>
        <input id="website" name="website" tabIndex={-1} autoComplete="off" />
      </div>

      <h2 className="text-xl font-extrabold tracking-[-0.04em] text-[#17214d]">{form.title}</h2>
      <p className="mt-2 text-[13px] leading-6 text-[#72809a]">{form.description}</p>

      <div className="mt-5 grid gap-4 sm:grid-cols-2">
        <Field label={form.fullName} name="fullName" error={state.errors?.fullName} required />
        <Field label={form.mobile} name="mobile" error={state.errors?.mobile} numericPhone required />
        <Field label={form.email} name="email" error={state.errors?.email} type="email" required />
        <Field label={form.company} name="company" error={state.errors?.company} required />
        {mode === "contact" ? (
          <label className="text-[12px] font-bold text-[#34405d]">
            {form.product}
            <select name="product" defaultValue="" required className={fieldClass}>
              <option value="" disabled>{form.selectProduct}</option>
              <option value="pureestate">PureEstate</option>
              <option value="buildpro">BuildPro</option>
              <option value="societypro">SocietyPro</option>
              <option value="not-sure">Not sure yet</option>
            </select>
            <ErrorText errors={state.errors?.product} />
          </label>
        ) : (
          <input type="hidden" name="product" value="not-sure" />
        )}
        <label className="text-[12px] font-bold text-[#34405d]">
          {form.preferredLanguage}
          <select name="preferredLanguage" defaultValue={locale} required className={fieldClass}>
            <option value="en">English</option>
            <option value="hi">हिन्दी</option>
            <option value="gu">ગુજરાતી</option>
          </select>
          <ErrorText errors={state.errors?.preferredLanguage} />
        </label>
      </div>

      <label className="mt-4 block text-[12px] font-bold text-[#34405d]">
        {form.message}
        <textarea
          name="message"
          rows={4}
          className={`${fieldClass} h-auto resize-y py-3`}
        />
        <ErrorText errors={state.errors?.message} />
      </label>

      {state.message ? (
        <p aria-live="polite" className="mt-4 text-[12px] font-semibold text-rose-600">
          {state.message}
        </p>
      ) : null}

      <button
        type="submit"
        disabled={pending}
        className="mt-5 inline-flex h-12 w-full items-center justify-center gap-2 rounded-lg bg-gradient-to-r from-[#5264ee] to-[#6555e9] px-5 text-[13px] font-bold text-white shadow-[0_8px_18px_rgba(93,91,238,0.24)] disabled:cursor-wait disabled:opacity-70"
      >
        {pending ? <LoaderCircle size={17} className="animate-spin" /> : <ArrowRight size={17} />}
        {pending ? form.sending : form.submit}
      </button>
      <p className="mt-3 text-[10px] leading-5 text-[#8c97aa]">{form.privacy}</p>
    </form>
  );
}

function Field({
  error,
  label,
  name,
  numericPhone = false,
  required,
  type = "text",
}: {
  error?: string[];
  label: string;
  name: string;
  numericPhone?: boolean;
  required?: boolean;
  type?: string;
}) {
  return (
    <label className="text-[12px] font-bold text-[#34405d]">
      {label}
      {numericPhone ? (
        <NumericPhoneInput className={fieldClass} name={name} required={required} />
      ) : (
        <input className={fieldClass} name={name} required={required} type={type} />
      )}
      <ErrorText errors={error} />
    </label>
  );
}

function ErrorText({ errors }: { errors?: string[] }) {
  return errors?.[0] ? <span className="mt-1 block text-[11px] text-rose-600">{errors[0]}</span> : null;
}
