'use client';

import { zodResolver } from '@hookform/resolvers/zod';
import { Briefcase, ChevronDown, Info, Mail, Phone, User } from 'lucide-react';
import Link from 'next/link';
import { useForm, type FieldError } from 'react-hook-form';

import {
  employeeDetailsSchema,
  type EmployeeDetailsFormData,
} from '@/features/employee-signup/schemas/employee-signup.schema';
import { isoCountrySelectOptions } from '@/constants/iso-countries';

/** ISO alpha-2 codes, not free text — the flight traveller form (and Amadeus
 *  itself) key nationality/issuing-country on the code, not the name typed
 *  here. A free-text field let through values that matched nothing there. */
const COUNTRY_OPTIONS = isoCountrySelectOptions();

const inputBase =
  'block h-[38px] w-full rounded-[var(--fra-radius-sm)] border border-[var(--fra-border-strong)] bg-[var(--fra-surface)] px-3 text-sm text-[var(--fra-text)] outline-none transition-colors placeholder:text-[var(--fra-muted)] hover:border-[var(--fra-muted)] focus:border-[var(--fra-navy-2)] focus:shadow-[0_0_0_3px_rgba(27,77,97,0.15)] disabled:bg-[var(--fra-surface-2)] disabled:text-[var(--fra-muted)]';
const invalidInput = 'border-[var(--fra-rejected)]! shadow-[0_0_0_3px_rgba(220,38,38,0.12)]';
const labelClass = 'mb-1.5 flex items-baseline gap-1 text-[13px] font-semibold text-[var(--fra-text)]';
const requiredMark = <em className="font-normal not-italic text-[var(--fra-coral)]">*</em>;

function cx(...parts: Array<string | false | undefined>): string {
  return parts.filter(Boolean).join(' ');
}

function FieldErrorText({ error }: { error?: FieldError }) {
  if (!error?.message) return null;
  return <p className="mt-1 text-xs text-[var(--fra-rejected)]">{error.message}</p>;
}

interface SelectFieldProps extends React.SelectHTMLAttributes<HTMLSelectElement> {
  invalid?: boolean;
}

function SelectField({ invalid, className, children, ...props }: SelectFieldProps) {
  return (
    <div className="relative">
      <select className={cx(inputBase, 'cursor-pointer appearance-none pr-8', invalid && invalidInput, className)} {...props}>
        {children}
      </select>
      <span className="pointer-events-none absolute inset-y-0 right-0 flex w-8 items-center justify-center text-[var(--fra-muted)]">
        <ChevronDown className="size-3.5" />
      </span>
    </div>
  );
}

interface FieldGroupProps {
  icon: React.ReactNode;
  title: string;
  note?: string;
  children: React.ReactNode;
  first?: boolean;
}

function FieldGroup({ icon, title, note, children, first }: FieldGroupProps) {
  return (
    <div
      role="group"
      aria-label={title}
      className={cx('border-b border-dashed border-[var(--fra-border)] py-5', first && 'pt-0')}
    >
      {/* Plain div + h3, not <fieldset>/<legend> — legends carry their own
          UA-specific box/positioning rules (they can visually offset from
          the fieldset's normal flow even once reset), which showed up here
          as the icon badge floating above the heading text. A heading
          sidesteps that entirely and is independently fine for a11y. */}
      <h3 className="mb-4 flex items-center gap-2.5 text-[15px] font-bold text-[var(--fra-heading)]">
        <span className="flex size-7 shrink-0 items-center justify-center rounded-full bg-[var(--fra-blue-bg)] text-[var(--fra-navy-2)]">
          {icon}
        </span>
        <span>{title}</span>
        {note && <small className="ml-0.5 text-xs font-medium text-[var(--fra-muted)]">{note}</small>}
      </h3>
      {children}
    </div>
  );
}

const GENDER_OPTIONS = [
  { value: 'M', label: 'Male' },
  { value: 'F', label: 'Female' },
];

interface YourDetailsStepProps {
  email: string;
  defaultValues?: Partial<EmployeeDetailsFormData>;
  submitting: boolean;
  errorMessage?: string | null;
  onSubmit: (data: EmployeeDetailsFormData) => void;
}

export default function YourDetailsStep({
  email,
  defaultValues,
  submitting,
  errorMessage,
  onSubmit,
}: YourDetailsStepProps) {
  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<EmployeeDetailsFormData>({
    resolver: zodResolver(employeeDetailsSchema),
    defaultValues: { workEmail: email, mobileCountryCode: '+1', ...defaultValues },
  });

  const today = new Date().toISOString().slice(0, 10);

  return (
    <form onSubmit={handleSubmit(onSubmit)} noValidate autoComplete="off">
      <h2 className="mb-1.5 text-[22px] font-extrabold text-[var(--fra-heading)]">
        Create your business travel account
      </h2>
      <p className="mb-0 text-sm text-[var(--fra-muted)]">
        We use these details to book your flights, so they must match your passport exactly.
      </p>

      <FieldGroup icon={<Briefcase className="size-3.5" />} title="Work details" first>
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div>
            <label className={labelClass} htmlFor="workEmail">
              Work email {requiredMark}
            </label>
            <div className="relative">
              <span className="pointer-events-none absolute inset-y-0 left-0 flex w-9 items-center justify-center text-[var(--fra-muted)]">
                <Mail className="size-[15px]" />
              </span>
              <input
                id="workEmail"
                type="email"
                className={cx(inputBase, 'pl-9', 'bg-[var(--fra-surface-2)] text-[var(--fra-muted)]')}
                value={email}
                disabled
                readOnly
              />
            </div>
          </div>
          <div>
            <label className={labelClass} htmlFor="employeeId">
              Employee ID
            </label>
            <input
              id="employeeId"
              className={cx(inputBase, 'uppercase', !!errors.employeeId && invalidInput)}
              placeholder="e.g. BD1234"
              maxLength={12}
              {...register('employeeId', {
                onChange: (e) => setValue('employeeId', e.target.value.toUpperCase().replace(/\s+/g, '')),
              })}
            />
            <FieldErrorText error={errors.employeeId} />
          </div>
          <div>
            <label className={labelClass} htmlFor="department">
              Department {requiredMark}
            </label>
            <input
              id="department"
              className={cx(inputBase, !!errors.department && invalidInput)}
              placeholder="e.g. Business Development"
              {...register('department')}
            />
            <FieldErrorText error={errors.department} />
          </div>
          <div>
            <label className={labelClass} htmlFor="officeLocation">
              Office location
            </label>
            <input
              id="officeLocation"
              className={cx(inputBase, !!errors.officeLocation && invalidInput)}
              placeholder="e.g. New York"
              {...register('officeLocation')}
            />
            <FieldErrorText error={errors.officeLocation} />
          </div>
        </div>
      </FieldGroup>

      <FieldGroup icon={<User className="size-3.5" />} title="Personal details" note="as per passport">
        <div className="mb-4 flex gap-2.5 rounded-xl border border-[var(--fra-pending-border)] bg-[var(--fra-pending-bg)] px-3.5 py-3">
          <Info className="mt-0.5 size-[18px] shrink-0 text-[var(--fra-pending)]" />
          <p className="m-0 text-[13px] leading-relaxed text-[var(--fra-text)]">
            Type your name <strong className="font-bold text-[var(--fra-heading)]">exactly as printed on your passport</strong>, including
            middle names — no nicknames or initials. Airlines can refuse boarding if the ticket name doesn&apos;t match.
          </p>
        </div>
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-12">
          <div className="sm:col-span-4">
            <label className={labelClass} htmlFor="firstName">
              First name {requiredMark}
            </label>
            <input
              id="firstName"
              className={cx(inputBase, 'uppercase', !!errors.firstName && invalidInput)}
              placeholder="As on passport"
              autoComplete="given-name"
              {...register('firstName')}
            />
            <FieldErrorText error={errors.firstName} />
          </div>
          <div className="col-span-1 sm:col-span-4">
            <label className={labelClass} htmlFor="middleName">
              Middle name
            </label>
            <input
              id="middleName"
              className={cx(inputBase, 'uppercase')}
              placeholder="If on passport"
              autoComplete="additional-name"
              {...register('middleName')}
            />
            <FieldErrorText error={errors.middleName} />
          </div>
          <div className="col-span-1 sm:col-span-4">
            <label className={labelClass} htmlFor="lastName">
              Surname {requiredMark}
            </label>
            <input
              id="lastName"
              className={cx(inputBase, 'uppercase', !!errors.lastName && invalidInput)}
              placeholder="As on passport"
              autoComplete="family-name"
              {...register('lastName')}
            />
            <FieldErrorText error={errors.lastName} />
          </div>

          <div className="sm:col-span-4">
            <label className={labelClass} htmlFor="gender">
              Gender {requiredMark}
            </label>
            <SelectField id="gender" invalid={!!errors.gender} {...register('gender')}>
              <option value="">Select</option>
              {GENDER_OPTIONS.map((g) => (
                <option key={g.value} value={g.value}>
                  {g.label}
                </option>
              ))}
            </SelectField>
            <FieldErrorText error={errors.gender} />
          </div>
          <div className="sm:col-span-4">
            <label className={labelClass} htmlFor="dateOfBirth">
              Date of birth {requiredMark}
            </label>
            <input
              id="dateOfBirth"
              type="date"
              max={today}
              autoComplete="bday"
              className={cx(inputBase, !!errors.dateOfBirth && invalidInput)}
              {...register('dateOfBirth')}
            />
            <FieldErrorText error={errors.dateOfBirth} />
          </div>
          <div className="sm:col-span-4">
            <label className={labelClass} htmlFor="nationality">
              Nationality {requiredMark}
            </label>
            <SelectField id="nationality" invalid={!!errors.nationality} {...register('nationality')}>
              <option value="">Select country</option>
              {COUNTRY_OPTIONS.map((c) => (
                <option key={c.code} value={c.code}>
                  {c.name}
                </option>
              ))}
            </SelectField>
            <FieldErrorText error={errors.nationality} />
          </div>

          <div className="sm:col-span-4">
            <label className={labelClass} htmlFor="passportNumber">
              Passport number {requiredMark}
            </label>
            <input
              id="passportNumber"
              className={cx(inputBase, 'uppercase', !!errors.passportNumber && invalidInput)}
              placeholder="e.g. X12345678"
              maxLength={9}
              {...register('passportNumber', {
                onChange: (e) => setValue('passportNumber', e.target.value.toUpperCase().replace(/\s+/g, '')),
              })}
            />
            <FieldErrorText error={errors.passportNumber} />
          </div>
          <div className="sm:col-span-4">
            <label className={labelClass} htmlFor="passportExpiry">
              Passport expiry date {requiredMark}
            </label>
            <input
              id="passportExpiry"
              type="date"
              min={today}
              className={cx(inputBase, !!errors.passportExpiry && invalidInput)}
              {...register('passportExpiry')}
            />
            <FieldErrorText error={errors.passportExpiry} />
          </div>
          <div className="sm:col-span-4">
            <label className={labelClass} htmlFor="passportIssuingCountry">
              Issuing country {requiredMark}
            </label>
            <SelectField
              id="passportIssuingCountry"
              invalid={!!errors.passportIssuingCountry}
              {...register('passportIssuingCountry')}
            >
              <option value="">Select country</option>
              {COUNTRY_OPTIONS.map((c) => (
                <option key={c.code} value={c.code}>
                  {c.name}
                </option>
              ))}
            </SelectField>
            <FieldErrorText error={errors.passportIssuingCountry} />
          </div>
        </div>
      </FieldGroup>

      <FieldGroup icon={<Phone className="size-3.5" />} title="Contact">
        <div className="sm:w-2/3">
          <label className={labelClass} htmlFor="mobileNumber">
            Mobile number {requiredMark}
          </label>
          <div className="flex gap-2">
            <div className="w-[140px] shrink-0 sm:w-[128px]">
              <SelectField aria-label="Country code" {...register('mobileCountryCode')}>
                <option value="+1">US / CA / PR +1</option>
                <option value="+44">UK +44</option>
                <option value="+971">UAE +971</option>
                <option value="+91">IN +91</option>
                <option value="+61">AU +61</option>
                <option value="+33">FR +33</option>
                <option value="+49">DE +49</option>
                <option value="+81">JP +81</option>
              </SelectField>
            </div>
            <input
              id="mobileNumber"
              type="tel"
              inputMode="tel"
              autoComplete="tel-national"
              placeholder="Mobile number"
              className={cx(inputBase, 'min-w-0 flex-1', !!errors.mobileNumber && invalidInput)}
              {...register('mobileNumber', {
                onChange: (e) => setValue('mobileNumber', e.target.value.replace(/[^\d\s()-]/g, '')),
              })}
            />
          </div>
          <FieldErrorText error={errors.mobileNumber} />
          <small className="mt-1 block text-xs text-[var(--fra-muted)]">
            For flight changes and delay alerts. Airlines may also need it.
          </small>
        </div>
      </FieldGroup>

      {errorMessage && (
        <p className="mt-4 rounded-[10px] bg-[var(--fra-rejected-bg)] px-3 py-2.5 text-[13px] text-[var(--fra-rejected)]">
          {errorMessage}
        </p>
      )}

      <label
        className={cx(
          'mt-4 flex cursor-pointer items-start gap-2.5 rounded-xl border border-[var(--fra-border)] bg-[var(--fra-surface-2)] px-3.5 py-3 text-[13px] leading-relaxed text-[var(--fra-text)]',
          !!errors.passportConfirmed && 'border-[var(--fra-rejected)] bg-[var(--fra-rejected-bg)]',
        )}
      >
        <input
          type="checkbox"
          className="mt-0.5 size-[18px] shrink-0 accent-[var(--fra-approved-solid)]"
          {...register('passportConfirmed')}
        />
        <span>
          I confirm my name, date of birth, nationality and passport details above exactly match my passport. I
          understand wrong details can stop me from flying.
        </span>
      </label>
      <FieldErrorText error={errors.passportConfirmed} />

      <button
        type="submit"
        disabled={submitting}
        className="group mt-4 flex h-11 w-full items-center justify-center gap-2 rounded-[var(--fra-radius-sm)] bg-[var(--fra-coral)] text-[15px] font-semibold text-white shadow-[0_4px_14px_rgba(244,93,107,0.35)] transition-colors hover:bg-[var(--fra-coral-dark)] disabled:cursor-not-allowed disabled:opacity-60"
      >
        <span>{submitting ? 'Creating account…' : 'Create account'}</span>
        {!submitting && (
          <svg
            className="size-4 transition-transform group-hover:translate-x-0.5"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2.5"
          >
            <path strokeLinecap="round" strokeLinejoin="round" d="M5 12h14M13 6l6 6-6 6" />
          </svg>
        )}
      </button>
      <p className="mt-4 mb-0 text-center text-[13px] text-[var(--fra-muted)]">
        Already have an account?{' '}
        <Link href="/employee-login" className="font-semibold text-[var(--fra-coral)] hover:underline">
          Sign in
        </Link>
      </p>
    </form>
  );
}
