'use client';

import { ArrowLeft, ArrowRight, ChevronRight, LoaderCircle, Lock, RotateCw } from 'lucide-react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { useEffect, useMemo, useRef, useState } from 'react';
import { toast } from 'sonner';

import { FormAlert } from '@/components/forms/form-field';
import { AddressStep } from '@/components/shipments/address-step';
import type { SavedAddress } from '@/components/shipments/address-picker';
import { ItemsTable } from '@/components/shipments/items-table';
import { OptionsStep } from '@/components/shipments/options-step';
import { ParcelFields } from '@/components/shipments/parcel-fields';
import { RateList } from '@/components/shipments/rate-list';
import { ReviewStep } from '@/components/shipments/review-step';
import { Stepper, WIZARD_STEPS } from '@/components/shipments/stepper';
import { TopUpModal } from '@/components/shipments/top-up-modal';
import { StepTransition, WizardFrame } from '@/components/shipments/wizard-frame';
import { Button } from '@/components/ui/button';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { ForbiddenState } from '@/components/ui/states';
import { Tooltip } from '@/components/ui/tooltip';
import { ApiError, api, apiResponse } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import { formatMoney, minorFromMajor } from '@/lib/money';
import { queryKeys } from '@/lib/query-keys';
import { usePermission } from '@/hooks/use-permission';
import type { MeResponse } from '@/shared/types';
import {
  DRAFT_STORAGE_KEY,
  addressIssues,
  addressPayload,
  declaredTotalMinor,
  emptyAddress,
  emptyDraft,
  fromMetric,
  isInternational,
  itemIssues,
  optionIssues,
  parcelIssues,
  purchaseFingerprint,
  quoteIsStale,
  rateFingerprint,
  rateRequest,
  readDraft,
  wizardStepForField,
  type AddressDraft,
  type SelectedQuote,
  type ShipmentDraft,
} from '@/lib/wizard';
import { addressFieldsSchema } from '@/shared/schemas/address';

interface RateResponse {
  options: SelectedQuote[];
  reasons: string[];
}

const fieldMessages = (details: unknown): Record<string, string> => {
  if (typeof details !== 'object' || details === null) return {};
  const source = 'fields' in details && typeof details.fields === 'object' && details.fields !== null ? details.fields : details;
  return Object.fromEntries(
    Object.entries(source).flatMap(([name, value]) => {
      if (typeof value === 'string') return [[name, value]];
      if (Array.isArray(value) && typeof value[0] === 'string') return [[name, value[0]]];
      return [];
    }),
  );
};

const savedCountry = (addresses: SavedAddress[], address: AddressDraft): string => {
  if (address.mode === 'saved') return addresses.find((item) => item.id === address.addressId)?.countryCode ?? '';
  return address.countryCode;
};

const savedCity = (addresses: SavedAddress[], address: AddressDraft): { city: string; countryCode: string } | null => {
  if (address.mode !== 'saved') return null;
  const found = addresses.find((item) => item.id === address.addressId);
  return found === undefined ? null : { city: found.city, countryCode: found.countryCode };
};

export function ShipmentWizard() {
  const allowed = usePermission('shipments:create');
  const canReadWallet = usePermission('wallet:read');
  const canReadSettings = usePermission('tenant:settings');
  const { user, tenant } = useAuth();
  const router = useRouter();
  const searchParams = useSearchParams();
  const headingRef = useRef<HTMLHeadingElement>(null);
  const [draft, setDraft] = useState<ShipmentDraft>(emptyDraft);
  const [draftReady, setDraftReady] = useState(false);
  const [addresses, setAddresses] = useState<SavedAddress[]>([]);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [rates, setRates] = useState<RateResponse>({ options: [], reasons: [] });
  const [rating, setRating] = useState(false);
  const [phase, setPhase] = useState<'creating' | 'buying' | null>(null);
  const [notice, setNotice] = useState<string | null>(null);
  const [confirmed, setConfirmed] = useState(false);
  const [summaryOpen, setSummaryOpen] = useState(false);
  const [topUpOpen, setTopUpOpen] = useState(false);
  const [pendingExit, setPendingExit] = useState<string | null>(null);
  const [maxStep, setMaxStep] = useState(draft.step);
  const currency = tenant?.currency ?? 'USD';
  const duplicate = searchParams.get('duplicate');
  const me = useQuery({ queryKey: queryKeys.me, queryFn: () => api<MeResponse>('/auth/me') });
  const wallet = useQuery({
    queryKey: queryKeys.wallet,
    enabled: canReadWallet,
    queryFn: () => api<{ balanceMinor: number; currency: string; lowBalance: boolean; provider: 'manual' | 'stripe' }>('/wallet'),
  });
  const settings = useQuery({
    queryKey: ['tenant-settings'] as const,
    enabled: canReadSettings,
    queryFn: () => api<{ defaultParcel?: Record<string, number> | null }>('/tenant'),
  });
  // Prefer the live /wallet query; /auth/me carries the same balance from when the session loaded.
  const balanceMinor = wallet.data?.balanceMinor ?? me.data?.wallet?.balanceMinor ?? 0;
  const paymentProvider = wallet.data?.provider ?? 'manual';

  useEffect(() => {
    const timer = window.setTimeout(() => {
      if (duplicate === null) {
        const stored = readDraft(sessionStorage.getItem(DRAFT_STORAGE_KEY));
        if (stored !== null) setDraft(stored);
      }
      setDraftReady(true);
    }, 0);
    return () => window.clearTimeout(timer);
  }, [duplicate]);

  useEffect(() => {
    if (!draftReady || duplicate !== null) return;
    sessionStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(draft));
  }, [draft, draftReady, duplicate]);

  useEffect(() => {
    void api<SavedAddress[]>('/addresses?pageSize=100')
      .then((rows) => {
        setAddresses(rows);
        const sender = rows.find((address) => address.isDefaultSender === true);
        setDraft((current) => {
          if (current.sender.addressId.length > 0 || current.sender.contactName.length > 0 || sender === undefined) return current;
          return { ...current, sender: { ...current.sender, mode: 'saved', addressId: sender.id } };
        });
      })
      .catch(() => undefined);
  }, []);

  useEffect(() => {
    if (duplicate === null) return;
    void api<Record<string, unknown>>(`/shipments/${duplicate}`).then((shipment) => {
      const origin = shipment.originAddress;
      const destination = shipment.destinationAddress;
      if (typeof origin !== 'object' || origin === null || typeof destination !== 'object' || destination === null) return;
      setDraft({
        ...emptyDraft(),
        sender: addressFromRecord(origin as Record<string, unknown>),
        recipient: addressFromRecord(destination as Record<string, unknown>),
        parcels: Array.isArray(shipment.parcels) ? shipment.parcels.map((parcel) => parcelFromRecord(parcel)) : emptyDraft().parcels,
        items: Array.isArray(shipment.items) ? shipment.items.map((item) => itemFromRecord(item, currency)) : [],
        taxesDutiesPaidBy: shipment.taxesDutiesPaidBy === 'Sender' ? 'Sender' : 'Recipient',
        isInsured: shipment.isInsured === true,
        reference: typeof shipment.reference === 'string' ? shipment.reference.slice(0, 50) : '',
      });
    }).catch(() => setNotice('The shipment to duplicate could not be loaded.'));
  }, [duplicate, currency]);

  useEffect(() => {
    headingRef.current?.focus();
  }, [draft.step]);

  const dirty = useMemo(() => purchaseFingerprint(draft) !== purchaseFingerprint(emptyDraft()), [draft]);
  useEffect(() => {
    const onLeave = (event: BeforeUnloadEvent) => {
      if (!dirty) return;
      event.preventDefault();
      event.returnValue = '';
    };
    const onClick = (event: MouseEvent) => {
      if (!dirty) return;
      const anchor = (event.target as Element | null)?.closest('a');
      if (anchor === null || anchor === undefined) return;
      const href = anchor.getAttribute('href');
      if (href === null || href.startsWith('#') || href.startsWith('/shipments/new')) return;
      if (anchor.origin !== window.location.origin && anchor.host.length > 0) return;
      event.preventDefault();
      setPendingExit(href);
    };
    window.addEventListener('beforeunload', onLeave);
    document.addEventListener('click', onClick, true);
    return () => {
      window.removeEventListener('beforeunload', onLeave);
      document.removeEventListener('click', onClick, true);
    };
  }, [dirty]);

  const international = isInternational(savedCountry(addresses, draft.sender), savedCountry(addresses, draft.recipient));
  if (!allowed) return <ForbiddenState />;

  const edit = (next: ShipmentDraft, clearQuote: boolean) => {
    const fingerprintChanged = purchaseFingerprint(next) !== purchaseFingerprint(draft);
    setDraft({
      ...next,
      idempotencyKey: fingerprintChanged ? null : draft.idempotencyKey,
      selectedQuote: clearQuote ? null : next.selectedQuote,
      quotedAt: clearQuote ? null : next.quotedAt,
      rateKey: clearQuote ? null : next.rateKey,
    });
    setErrors({});
  };

  const showErrors = (next: Record<string, string>) => {
    setErrors(next);
    const first = Object.keys(next)[0];
    if (first === undefined) return;
    const node = document.querySelector<HTMLElement>('[aria-invalid="true"], input, select, textarea');
    node?.focus();
    window.scrollTo({ top: 0 });
  };

  const validateStep = (step: number): Record<string, string> => {
    if (step === 0) return { ...prefix('sender', addressIssues(draft.sender)), ...prefix('recipient', addressIssues(draft.recipient)) };
    if (step === 1) return { ...parcelIssues(draft), ...itemIssues(draft, international) };
    if (step === 2) return optionIssues(draft);
    if (step === 3 && draft.selectedQuote === null) return { quote: 'Choose a courier.' };
    return {};
  };

  const goTo = (step: number) => {
    setDraft((current) => ({
      ...current,
      step,
      idempotencyKey: step === 4 ? (current.idempotencyKey ?? crypto.randomUUID()) : current.idempotencyKey,
    }));
    setMaxStep((current) => Math.max(current, step));
  };

  const next = async () => {
    const nextErrors = validateStep(draft.step);
    if (Object.keys(nextErrors).length > 0) {
      showErrors(nextErrors);
      return;
    }
    if (draft.step === 0) {
      const senderId = await ensureAddress(draft.sender, 'SENDER');
      if (senderId === null) return;
      edit({ ...draft, sender: { ...draft.sender, mode: 'saved', addressId: senderId }, step: 1 }, true);
      setMaxStep((current) => Math.max(current, 1));
      return;
    }
    goTo(Math.min(4, draft.step + 1));
  };

  const ensureAddress = async (address: AddressDraft, type: 'SENDER' | 'RECIPIENT'): Promise<string | null> => {
    if (address.mode === 'saved') return address.addressId;
    try {
      const created = await api<SavedAddress>('/addresses', {
        json: { ...addressPayload(address), type, ...(type === 'SENDER' && address.saveToBook ? { isDefaultSender: false } : {}) },
      });
      setAddresses((current) => [...current, created]);
      return created.id;
    } catch (error) {
      setNotice(error instanceof ApiError ? error.message : 'The address could not be saved.');
      return null;
    }
  };

  const loadRates = async (force: boolean) => {
    const senderId = draft.sender.addressId;
    const body = rateRequest(draft, senderId);
    if (body === null) {
      setNotice('Complete the addresses before comparing rates.');
      goTo(0);
      return;
    }
    const key = rateFingerprint(body);
    if (!force && key === draft.rateKey && rates.options.length > 0) return;
    setRating(true);
    setNotice(null);
    try {
      const result = await api<RateResponse>('/rates', { json: body });
      setRates(result);
      setDraft((current) => ({ ...current, rateKey: key, quotedAt: new Date().toISOString(), selectedQuote: null, idempotencyKey: null }));
    } catch (error) {
      if (error instanceof ApiError && error.status === 422) {
        const messages = fieldMessages(error.details);
        const names = Object.keys(messages);
        const step = names.length === 0 ? 1 : Math.min(...names.map((name) => wizardStepForField(name)));
        setErrors(messages);
        goTo(step);
        setNotice(error.message);
      } else {
        setNotice(error instanceof ApiError ? error.message : 'Rates could not be loaded.');
      }
    } finally {
      setRating(false);
    }
  };

  const buy = async () => {
    if (!confirmed || draft.selectedQuote === null || phase !== null) return;
    const senderId = draft.sender.addressId;
    let destinationId = draft.recipient.mode === 'saved' ? draft.recipient.addressId : undefined;
    if (draft.recipient.mode === 'new' && draft.recipient.saveToBook) {
      const created = await ensureAddress(draft.recipient, 'RECIPIENT');
      if (created === null) return;
      destinationId = created;
    }
    const destination = destinationId === undefined ? addressFieldsSchema.safeParse(addressPayload(draft.recipient)) : null;
    if (destination !== null && !destination.success) {
      setNotice('Check the recipient address.');
      goTo(0);
      return;
    }
    const request = rateRequest(draft, senderId, destinationId);
    if (request === null) {
      setNotice('Check the parcel and item details.');
      goTo(1);
      return;
    }
    const idempotencyKey = draft.idempotencyKey ?? crypto.randomUUID();
    setDraft((current) => ({ ...current, idempotencyKey }));
    setPhase('creating');
    const timer = window.setTimeout(() => setPhase('buying'), 700);
    try {
      const insured = draft.isInsured ? minorFromMajor(draft.insuredAmount) : undefined;
      const result = await apiResponse<{ id: string }>('/shipments', {
        headers: { 'Idempotency-Key': idempotencyKey },
        json: {
          ...(draft.reference.trim().length === 0 ? {} : { reference: draft.reference.trim() }),
          originAddressId: senderId,
          ...(destinationId === undefined ? {} : { destinationAddressId: destinationId }),
          ...(destinationId === undefined && destination?.success ? { destination: destination.data } : {}),
          parcels: request.parcels,
          items: request.items,
          taxesDutiesPaidBy: draft.taxesDutiesPaidBy,
          isInsured: draft.isInsured,
          ...(insured === undefined || insured === null ? {} : { insuredAmountMinor: insured }),
          quoteToken: draft.selectedQuote.quoteToken,
          courierServiceId: draft.selectedQuote.courierServiceId,
          ...(draft.notes.trim().length === 0 ? {} : { notes: draft.notes.trim() }),
        },
      });
      if (!draft.sender.saveToBook) {
        await api(`/addresses/${senderId}`, { method: 'DELETE' }).catch(() => undefined);
      }
      sessionStorage.removeItem(DRAFT_STORAGE_KEY);
      router.push(`/shipments/${result.data.id}?created=1`);
    } catch (error) {
      if (error instanceof ApiError && error.code === 'QUOTE_INVALID') {
        setNotice('The quoted rate is no longer valid. Request new rates.');
        setDraft((current) => ({ ...current, step: 3, selectedQuote: null, rateKey: null }));
        void loadRates(true);
      } else if (error instanceof ApiError && error.code === 'INSUFFICIENT_FUNDS') {
        setNotice(error.message);
        setTopUpOpen(true);
      } else if (error instanceof ApiError && (error.status === 502 || error.status === 0)) {
        setNotice('Something went wrong. Your wallet is only charged once.');
      } else if (error instanceof ApiError && error.status === 422) {
        const messages = fieldMessages(error.details);
        const names = Object.keys(messages);
        if (names.length > 0) {
          setErrors(messages);
          goTo(Math.min(...names.map((name) => wizardStepForField(name))));
        }
        setNotice(error.message);
      } else {
        setNotice(error instanceof ApiError ? error.message : 'Something went wrong. Your wallet is only charged once.');
      }
    } finally {
      window.clearTimeout(timer);
      setPhase(null);
    }
  };

  const quote = draft.selectedQuote;
  const shortfall = quote === null ? 0 : Math.max(0, quote.totalMinor - balanceMinor);
  const emailUnverified = user?.emailVerifiedAt === undefined;
  const confirmBlocker =
    quote === null ? 'Choose a courier first.' : emailUnverified ? 'Verify your email before buying a label.' : shortfall > 0 ? 'Top up your wallet to cover the total.' : !confirmed ? 'Tick the confirmation box above.' : null;
  const busy = phase !== null;

  const confirmButton = (
    <Button
      type="button"
      size="lg"
      className="h-14 min-h-14 w-full px-6 text-[16px] sm:w-auto"
      disabled={confirmBlocker !== null || busy}
      aria-describedby={confirmBlocker === null ? undefined : 'confirm-blocker'}
      onClick={() => void buy()}
    >
      {busy ? (
        <span className="inline-flex items-center gap-3" role="status" aria-live="polite">
          <LoaderCircle className="h-4 w-4 animate-spin" aria-hidden="true" />
          <span className="inline-flex items-center gap-2 text-small">
            <span className={phase === 'creating' ? 'font-semibold' : 'opacity-60'}>Creating shipment</span>
            <ChevronRight className="h-3.5 w-3.5 opacity-60" aria-hidden="true" />
            <span className={phase === 'buying' ? 'font-semibold' : 'opacity-60'}>Buying label</span>
          </span>
        </span>
      ) : (
        <>
          <Lock className="h-4 w-4" aria-hidden="true" />
          Confirm and pay {quote === null ? '' : formatMoney(quote.totalMinor, quote.currency)}
        </>
      )}
    </Button>
  );

  return (
    <WizardFrame
      draft={draft}
      sender={savedCity(addresses, draft.sender)}
      recipient={savedCity(addresses, draft.recipient)}
      international={international}
      balanceMinor={balanceMinor}
      currency={currency}
      summaryOpen={summaryOpen}
      onToggleSummary={setSummaryOpen}
      onSaveDraft={() => toast.success('Draft saved.')}
      back={
        <Button type="button" variant="secondary" size="lg" disabled={draft.step === 0 || busy} onClick={() => goTo(draft.step - 1)}>
          <ArrowLeft className="h-4 w-4" aria-hidden="true" />
          Back
        </Button>
      }
      primary={
        draft.step < 4 ? (
          <Button type="button" size="lg" className="group" onClick={() => void next()}>
            Continue
            <ArrowRight className="h-4 w-4 transition-transform duration-180 group-hover:translate-x-[3px]" aria-hidden="true" />
          </Button>
        ) : confirmBlocker !== null && !busy ? (
          <Tooltip label={confirmBlocker} side="top">
            <span className="inline-flex w-full sm:w-auto" tabIndex={0}>
              {confirmButton}
            </span>
          </Tooltip>
        ) : (
          confirmButton
        )
      }
    >
      <Stepper step={draft.step} maxReachable={maxStep} onSelect={(step) => { if (step <= maxStep) goTo(step); }} />
      <div>
        <h2 ref={headingRef} tabIndex={-1} className="font-display text-h2 font-bold outline-none">
          {WIZARD_STEPS[draft.step]}
        </h2>
        <p className="mt-1 text-small text-muted-foreground">{STEP_HINTS[draft.step]}</p>
        {draft.step === 4 && confirmBlocker !== null ? (
          <p id="confirm-blocker" className="sr-only">
            {confirmBlocker}
          </p>
        ) : null}
      </div>
      {notice === null ? null : (
        <FormAlert
          tone={draft.step === 4 ? 'error' : 'warning'}
          action={
            draft.step === 4 && quote !== null && confirmBlocker === null ? (
              <Button type="button" size="sm" variant="secondary" disabled={busy} onClick={() => void buy()}>
                <RotateCw className="h-3.5 w-3.5" aria-hidden="true" />
                Try again
              </Button>
            ) : undefined
          }
        >
          {notice}
        </FormAlert>
      )}
      <StepTransition step={draft.step}>
        {draft.step === 0 ? <AddressStep draft={draft} addresses={addresses} errors={errors} onEdit={(next) => edit(next, true)} /> : null}
        {draft.step === 1 ? (
          <div className="grid gap-6">
            <ParcelFields
              draft={draft}
              errors={errors}
              onChange={(parcels) => edit({ ...draft, parcels }, true)}
              onUnit={(unit) => edit({ ...draft, unit }, true)}
              defaultParcel={defaultParcel(settings.data?.defaultParcel)}
              onPreset={(preset) => edit({
                ...draft,
                parcels: [{ weight: fromMetric(preset.weightKg, draft.unit, 'weight'), length: fromMetric(preset.lengthCm, draft.unit, 'length'), width: fromMetric(preset.widthCm, draft.unit, 'length'), height: fromMetric(preset.heightCm, draft.unit, 'length') }],
              }, true)}
            />
            <ItemsTable draft={draft} errors={errors} currency={currency} international={international} onChange={(items) => edit({ ...draft, items, insuredAmount: draft.insuredAmount || major(declaredTotalMinor({ ...draft, items })) }, true)} />
          </div>
        ) : null}
        {draft.step === 2 ? (
          <OptionsStep draft={draft} errors={errors} international={international} currency={currency} onEdit={(next, clearQuote) => edit(next, clearQuote)} />
        ) : null}
        {draft.step === 3 ? (
          <RateStep
            draft={draft}
            rates={rates}
            rating={rating}
            onEnter={() => void loadRates(false)}
            onRefresh={() => void loadRates(true)}
            onBack={() => goTo(2)}
            onSelect={(selected) => edit({ ...draft, selectedQuote: selected }, false)}
          />
        ) : null}
        {draft.step === 4 && quote !== null ? (
          <ReviewStep
            draft={draft}
            quote={quote}
            addresses={addresses}
            international={international}
            balanceMinor={balanceMinor}
            emailUnverified={emailUnverified}
            confirmed={confirmed}
            disabled={busy}
            onConfirmedChange={setConfirmed}
            onEditStep={goTo}
            onTopUp={() => setTopUpOpen(true)}
          />
        ) : null}
      </StepTransition>
      <TopUpModal open={topUpOpen} currency={currency} provider={paymentProvider} onClose={() => setTopUpOpen(false)} />
      <ConfirmDialog
        open={pendingExit !== null}
        title="Leave this shipment?"
        message="You have unsaved wizard changes. The draft stays in this browser until you clear it."
        onClose={() => setPendingExit(null)}
        onConfirm={() => {
          const href = pendingExit;
          setPendingExit(null);
          if (href !== null) router.push(href);
        }}
      />
    </WizardFrame>
  );
}

const STEP_HINTS = [
  'Where the parcel ships from and where it is going.',
  'Parcel size and weight, plus what is inside.',
  'Duties, insurance and your own reference.',
  'Compare couriers and pick a service.',
  'Check everything, then buy the label.',
] as const;

function RateStep({
  draft,
  rates,
  rating,
  onEnter,
  onRefresh,
  onBack,
  onSelect,
}: {
  draft: ShipmentDraft;
  rates: RateResponse;
  rating: boolean;
  onEnter: () => void;
  onRefresh: () => void;
  onBack: () => void;
  onSelect: (quote: SelectedQuote) => void;
}) {
  const started = useRef(false);
  useEffect(() => {
    if (started.current) return;
    started.current = true;
    onEnter();
  }, [onEnter]);
  return (
    <RateList
      options={rates.options}
      reasons={rates.reasons}
      loading={rating}
      selectedToken={draft.selectedQuote?.quoteToken ?? null}
      stale={quoteIsStale(draft.quotedAt)}
      quotedAt={draft.quotedAt}
      onSelect={onSelect}
      onRefresh={onRefresh}
      onBack={onBack}
    />
  );
}

const prefix = (scope: string, errors: Record<string, string>): Record<string, string> =>
  Object.fromEntries(Object.entries(errors).map(([key, value]) => [`${scope}.${key}`, value]));

const major = (minor: number): string => `${Math.floor(minor / 100)}.${String(minor % 100).padStart(2, '0')}`;

const defaultParcel = (value: Record<string, number> | null | undefined): { weightKg: number; lengthCm: number; widthCm: number; heightCm: number } | null => {
  if (value === null || value === undefined) return null;
  const weightKg = value.weightKg ?? value.weight;
  const lengthCm = value.lengthCm ?? value.length;
  const widthCm = value.widthCm ?? value.width;
  const heightCm = value.heightCm ?? value.height;
  if (weightKg === undefined || lengthCm === undefined || widthCm === undefined || heightCm === undefined) return null;
  return { weightKg, lengthCm, widthCm, heightCm };
};

const text = (value: unknown): string => (typeof value === 'string' ? value : '');

const addressFromRecord = (address: Record<string, unknown>): AddressDraft => ({
  ...emptyAddress(),
  mode: 'new',
  saveToBook: false,
  contactName: text(address.contactName),
  companyName: text(address.companyName),
  email: text(address.email),
  phone: text(address.phone),
  line1: text(address.line1),
  line2: text(address.line2),
  city: text(address.city),
  state: text(address.state),
  postalCode: text(address.postalCode),
  countryCode: text(address.countryCode),
});

const parcelFromRecord = (value: unknown): ShipmentDraft['parcels'][number] => {
  const parcel = typeof value === 'object' && value !== null ? value : {};
  const read = (key: string): string => (key in parcel && typeof parcel[key as keyof typeof parcel] === 'number' ? String(parcel[key as keyof typeof parcel]) : '');
  return { weight: read('weightKg'), length: read('lengthCm'), width: read('widthCm'), height: read('heightCm') };
};

const itemFromRecord = (value: unknown, currency: string): ShipmentDraft['items'][number] => {
  const item = typeof value === 'object' && value !== null ? value : {};
  const declared = 'declaredValueMinor' in item && typeof item.declaredValueMinor === 'number' ? major(item.declaredValueMinor) : '';
  return {
    description: text('description' in item ? item.description : ''),
    quantity: 'quantity' in item && typeof item.quantity === 'number' ? String(item.quantity) : '1',
    declaredValue: declared,
    currency: text('currency' in item ? item.currency : currency) || currency,
    hsCode: text('hsCode' in item ? item.hsCode : ''),
    originCountryCode: text('originCountryCode' in item ? item.originCountryCode : ''),
    sku: text('sku' in item ? item.sku : ''),
  };
};
