'use client';

import { Building2, Mail, Phone, User } from 'lucide-react';

import { describedBy, FormField } from '@/components/forms/form-field';
import { CountryCombobox } from '@/components/shipments/country-combobox';
import { Checkbox, Input, Select } from '@/components/ui/input';
import { regionLabels, SUBDIVISIONS } from '@/lib/regions';
import type { AddressDraft } from '@/lib/wizard';

export function AddressFields({
  idPrefix,
  value,
  errors,
  onChange,
  showSaveOption = true,
}: {
  idPrefix: string;
  value: AddressDraft;
  errors: Record<string, string>;
  onChange: (patch: Partial<AddressDraft>) => void;
  showSaveOption?: boolean;
}) {
  const labels = regionLabels(value.countryCode);
  const subdivisions = SUBDIVISIONS[value.countryCode];
  const field = (name: string) => ({
    'aria-invalid': errors[name] !== undefined ? true : undefined,
    'aria-describedby': describedBy(`${idPrefix}-${name}`, undefined, errors[name]),
  });
  return (
    <div className="grid gap-4 sm:grid-cols-2">
      <FormField id={`${idPrefix}-contactName`} label="Contact name" error={errors.contactName}>
        <Input id={`${idPrefix}-contactName`} autoComplete="name" leading={<User />} value={value.contactName} onChange={(event) => onChange({ contactName: event.target.value })} {...field('contactName')} />
      </FormField>
      <FormField id={`${idPrefix}-companyName`} label="Company (optional)" error={errors.companyName}>
        <Input id={`${idPrefix}-companyName`} autoComplete="organization" leading={<Building2 />} value={value.companyName} onChange={(event) => onChange({ companyName: event.target.value })} {...field('companyName')} />
      </FormField>
      <FormField id={`${idPrefix}-email`} label="Email (optional)" error={errors.email}>
        <Input id={`${idPrefix}-email`} type="email" autoComplete="email" leading={<Mail />} value={value.email} onChange={(event) => onChange({ email: event.target.value })} {...field('email')} />
      </FormField>
      <FormField id={`${idPrefix}-phone`} label="Phone" hint="Include the country code, for example +49 30 1234567." error={errors.phone}>
        <Input
          id={`${idPrefix}-phone`}
          inputMode="tel"
          autoComplete="tel"
          leading={<Phone />}
          value={value.phone}
          onChange={(event) => onChange({ phone: event.target.value })}
          aria-invalid={errors.phone !== undefined ? true : undefined}
          aria-describedby={describedBy(`${idPrefix}-phone`, 'hint', errors.phone)}
        />
      </FormField>
      <FormField id={`${idPrefix}-line1`} label="Address line 1" error={errors.line1} className="sm:col-span-2">
        <Input id={`${idPrefix}-line1`} autoComplete="address-line1" value={value.line1} onChange={(event) => onChange({ line1: event.target.value })} {...field('line1')} />
      </FormField>
      <FormField id={`${idPrefix}-line2`} label="Address line 2 (optional)" error={errors.line2} className="sm:col-span-2">
        <Input id={`${idPrefix}-line2`} autoComplete="address-line2" value={value.line2} onChange={(event) => onChange({ line2: event.target.value })} {...field('line2')} />
      </FormField>
      <FormField id={`${idPrefix}-city`} label="City" error={errors.city}>
        <Input id={`${idPrefix}-city`} autoComplete="address-level2" value={value.city} onChange={(event) => onChange({ city: event.target.value })} {...field('city')} />
      </FormField>
      <FormField id={`${idPrefix}-state`} label={labels.state} error={errors.state}>
        {subdivisions === undefined ? (
          <Input id={`${idPrefix}-state`} autoComplete="address-level1" value={value.state} onChange={(event) => onChange({ state: event.target.value })} {...field('state')} />
        ) : (
          <Select id={`${idPrefix}-state`} value={value.state} onChange={(event) => onChange({ state: event.target.value })} {...field('state')}>
            <option value="">Select</option>
            {subdivisions.map((region) => (
              <option key={region.code} value={region.code}>
                {region.name}
              </option>
            ))}
          </Select>
        )}
      </FormField>
      <FormField id={`${idPrefix}-postalCode`} label={labels.postal} error={errors.postalCode}>
        <Input id={`${idPrefix}-postalCode`} autoComplete="postal-code" value={value.postalCode} onChange={(event) => onChange({ postalCode: event.target.value })} {...field('postalCode')} />
      </FormField>
      <FormField id={`${idPrefix}-countryCode`} label="Country" error={errors.countryCode}>
        <CountryCombobox
          id={`${idPrefix}-countryCode`}
          value={value.countryCode}
          onChange={(countryCode) => onChange({ countryCode, state: '' })}
          invalid={errors.countryCode !== undefined}
          describedBy={describedBy(`${idPrefix}-countryCode`, undefined, errors.countryCode)}
        />
      </FormField>
      {showSaveOption ? (
        <label className="flex cursor-pointer items-center gap-2.5 rounded-lg border border-dashed border-border px-3 py-2.5 text-small font-medium sm:col-span-2">
          <Checkbox className="mt-0" checked={value.saveToBook} onChange={(event) => onChange({ saveToBook: event.target.checked })} />
          Save to my address book
        </label>
      ) : null}
    </div>
  );
}
