'use client';

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

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

/**
 * Step 1 of company sign-up (LEIS-958). There is no design for this flow yet
 * (see CompanySignupFlow's doc comment), so the field styling, icons and
 * FieldGroup convention are carried over from employee-signup's
 * YourDetailsStep as-is, for one visual language across every "create your
 * account" page in this app rather than a one-off look for this form.
 *
 * The admin is also a traveller, so this form takes the same passport-exact
 * "Personal details" block as the employee form — same fields, same rules
 * (picked straight off employeeDetailsSchema rather than copied) — so they can
 * book a flight for themselves as soon as the company exists.
 */

/** ISO alpha-2 codes, not free text: the flight traveller form (and Amadeus) key
 *  nationality/issuing-country on the code. */
const COUNTRY_OPTIONS = isoCountrySelectOptions();

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

export const companyDetailsSchema = z.object({
  workEmail: z.string().trim().min(1, 'Enter a valid work email.').email('Enter a valid work email.'),
  companyName: z
    .string()
    .trim()
    .min(2, 'Enter your company name.')
    .max(150, 'Keep your company name under 150 characters.'),
  businessAddress: z
    .string()
    .trim()
    .min(5, 'Enter your business address.')
    .max(300, 'Keep your business address under 300 characters.'),
  ...employeeDetailsSchema.pick({
    firstName: true,
    middleName: true,
    lastName: true,
    gender: true,
    dateOfBirth: true,
    nationality: true,
    passportNumber: true,
    passportExpiry: true,
    passportIssuingCountry: true,
  }).shape,
});
export type CompanyDetailsFormData = z.infer<typeof companyDetailsSchema>;

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)]';
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')}>
      <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>
  );
}

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

export default function CompanyDetailsStep({ defaultValues, submitting, errorMessage, onSubmit }: CompanyDetailsStepProps) {
  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<CompanyDetailsFormData>({
    resolver: zodResolver(companyDetailsSchema),
    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)]">Set up your company</h2>
      <p className="mb-0 text-sm text-[var(--fra-muted)]">
        You&apos;ll be the company admin. We&apos;ll send a code to your work email to confirm it before anything is created.
      </p>

      <FieldGroup icon={<Building2 className="size-3.5" />} title="Company details" first>
        {/* Both fields full width. `companyName` used to sit in one half of a
            two-column row with nothing beside it, so a short input and a long
            one stacked with a ragged right edge (LEIS-1046). */}
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="sm:col-span-2">
            <label className={labelClass} htmlFor="companyName">
              Company name {requiredMark}
            </label>
            <input
              id="companyName"
              className={cx(inputBase, !!errors.companyName && invalidInput)}
              placeholder="e.g. Acme Corp"
              autoComplete="organization"
              {...register('companyName')}
            />
            <FieldErrorText error={errors.companyName} />
          </div>
          <div className="sm:col-span-2">
            <label className={labelClass} htmlFor="businessAddress">
              Business address {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)]">
                <MapPin className="size-[15px]" />
              </span>
              <input
                id="businessAddress"
                className={cx(inputBase, 'pl-9', !!errors.businessAddress && invalidInput)}
                placeholder="Street, city, state, country"
                autoComplete="street-address"
                {...register('businessAddress')}
              />
            </div>
            <FieldErrorText error={errors.businessAddress} />
          </div>
        </div>
      </FieldGroup>

      <FieldGroup icon={<Mail className="size-3.5" />} title="Your details" note="as the company admin">
        {/* One field, so it takes the row. This was a two-column grid holding
            "Your name" and "Work email"; LEIS-958 moved the name into Personal
            details below as First/Middle/Surname and left the email behind at
            half width with an empty cell beside it. */}
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="sm:col-span-2">
            <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', !!errors.workEmail && invalidInput)}
                placeholder="name@company.com"
                autoComplete="email"
                {...register('workEmail')}
              />
            </div>
            <FieldErrorText error={errors.workEmail} />
          </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', !!errors.middleName && invalidInput)}
              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>

      {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>
      )}

      <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 ? 'Sending code…' : 'Send verification code'}</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>
  );
}
