'use client';

const COUNTRIES: Array<[string, string]> = [
  ['US', 'United States'],
  ['CA', 'Canada'],
  ['GB', 'United Kingdom'],
  ['IE', 'Ireland'],
  ['IN', 'India'],
  ['AU', 'Australia'],
  ['SG', 'Singapore'],
  ['AE', 'United Arab Emirates'],
  ['DE', 'Germany'],
  ['FR', 'France'],
];

export type AddressMode = 'company' | 'new';

export interface BillingAddressValue {
  line1: string;
  city: string;
  region: string;
  postal: string;
  country: string;
}

export interface BillingAddressErrors {
  line1?: string;
  city?: string;
  postal?: string;
}

interface BillingAddressFieldsProps {
  /** Keeps field ids unique when AddCardForm and this modal are ever both in the DOM. */
  idPrefix: string;
  /** Null when the company has no address on file — the "use company address" option isn't offered then. */
  companyAddress: string | null;
  mode: AddressMode;
  onModeChange: (mode: AddressMode) => void;
  value: BillingAddressValue;
  onChange: (value: BillingAddressValue) => void;
  errors: BillingAddressErrors;
  onClearError: (field: keyof BillingAddressErrors) => void;
}

/**
 * The "Use company address" / "Enter a new address" section, shared by
 * AddCardForm and ChangeAddressModal (LEIS-968) rather than duplicated —
 * same simplified two-option shape as AddCardForm's own doc comment
 * explains (the ticket's literal spec, not the design's richer N-saved-
 * addresses picker).
 */
export default function BillingAddressFields({
  idPrefix,
  companyAddress,
  mode,
  onModeChange,
  value,
  onChange,
  errors,
  onClearError,
}: BillingAddressFieldsProps) {
  const set = (patch: Partial<BillingAddressValue>) => onChange({ ...value, ...patch });
  const titleId = `${idPrefix}AddrTitle`;

  return (
    <div className="bc-address" role="group" aria-labelledby={titleId}>
      <p className="bc-legend" id={titleId}>
        Billing address
      </p>
      {companyAddress && (
        <div className="bc-addr-opts" role="radiogroup" aria-labelledby={titleId}>
          <label className="bc-addr-opt">
            <input type="radio" name={`${idPrefix}AddrPick`} checked={mode === 'company'} onChange={() => onModeChange('company')} />
            <span>
              <strong>Use company address</strong>
              <small>{companyAddress}</small>
            </span>
          </label>
          <label className="bc-addr-opt is-new">
            <input type="radio" name={`${idPrefix}AddrPick`} checked={mode === 'new'} onChange={() => onModeChange('new')} />
            <span>
              <strong>Enter a new address</strong>
            </span>
          </label>
        </div>
      )}

      {mode === 'new' && (
        <div className="bc-addr-new">
          <div className="bc-field">
            <label className="bz-label" htmlFor={`${idPrefix}Line1`}>
              Street address
            </label>
            <input
              type="text"
              className={`bz-input${errors.line1 ? ' is-invalid' : ''}`}
              id={`${idPrefix}Line1`}
              autoComplete="billing address-line1"
              placeholder="Street and number, suite"
              maxLength={80}
              value={value.line1}
              onChange={(e) => {
                set({ line1: e.target.value });
                onClearError('line1');
              }}
            />
            {errors.line1 && <span className="bz-error">{errors.line1}</span>}
          </div>
          <div className="bc-row">
            <div className="bc-field">
              <label className="bz-label" htmlFor={`${idPrefix}City`}>
                City
              </label>
              <input
                type="text"
                className={`bz-input${errors.city ? ' is-invalid' : ''}`}
                id={`${idPrefix}City`}
                autoComplete="billing address-level2"
                placeholder="City"
                maxLength={40}
                value={value.city}
                onChange={(e) => {
                  set({ city: e.target.value });
                  onClearError('city');
                }}
              />
              {errors.city && <span className="bz-error">{errors.city}</span>}
            </div>
            <div className="bc-field">
              <label className="bz-label" htmlFor={`${idPrefix}Region`}>
                State / region
              </label>
              <input
                type="text"
                className="bz-input"
                id={`${idPrefix}Region`}
                autoComplete="billing address-level1"
                placeholder="e.g. CA"
                maxLength={30}
                value={value.region}
                onChange={(e) => set({ region: e.target.value })}
              />
            </div>
          </div>
          <div className="bc-row">
            <div className="bc-field">
              <label className="bz-label" htmlFor={`${idPrefix}Postal`}>
                Postal code
              </label>
              <input
                type="text"
                className={`bz-input${errors.postal ? ' is-invalid' : ''}`}
                id={`${idPrefix}Postal`}
                autoComplete="billing postal-code"
                placeholder="Postal code"
                maxLength={10}
                value={value.postal}
                onChange={(e) => {
                  set({ postal: e.target.value });
                  onClearError('postal');
                }}
              />
              {errors.postal && <span className="bz-error">{errors.postal}</span>}
            </div>
            <div className="bc-field">
              <label className="bz-label" htmlFor={`${idPrefix}Country`}>
                Country
              </label>
              <div className="bz-select">
                <select
                  className="bz-input"
                  id={`${idPrefix}Country`}
                  autoComplete="billing country"
                  value={value.country}
                  onChange={(e) => set({ country: e.target.value })}
                >
                  {COUNTRIES.map(([code, name]) => (
                    <option key={code} value={code}>
                      {name}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/** Shared postal-code shape check, same as AddCardForm's own validate(). */
export function validateNewAddress(mode: AddressMode, value: BillingAddressValue): BillingAddressErrors {
  if (mode !== 'new') return {};
  const err: BillingAddressErrors = {};
  if (!value.line1.trim()) err.line1 = 'Enter the street address.';
  if (!value.city.trim()) err.city = 'Enter the city.';
  if (!/^[A-Za-z0-9 -]{3,10}$/.test(value.postal.trim())) err.postal = 'Enter a valid postal code.';
  return err;
}
