'use client';

import { ArrowUpDown, MapPin, PackageOpen, Pencil, type LucideIcon } from 'lucide-react';
import { useState } from 'react';

import { describedBy, FieldError } from '@/components/forms/form-field';
import { AddressFields } from '@/components/shipments/address-fields';
import { AddressPicker, type SavedAddress } from '@/components/shipments/address-picker';
import { Button } from '@/components/ui/button';
import { Segmented } from '@/components/ui/segmented';
import { countryName, flagEmoji } from '@/lib/format';
import { emptyAddress, type AddressDraft, type ShipmentDraft } from '@/lib/wizard';

const unprefix = (scope: string, errors: Record<string, string>): Record<string, string> =>
  Object.fromEntries(Object.entries(errors).flatMap(([key, value]) => (key.startsWith(`${scope}.`) ? [[key.slice(scope.length + 1), value]] : [])));

/** Copies a saved address into editable fields ("Edit details"). */
const fromSaved = (saved: SavedAddress): AddressDraft => ({
  ...emptyAddress(),
  mode: 'new',
  saveToBook: false,
  contactName: saved.contactName,
  companyName: saved.companyName ?? '',
  email: saved.email ?? '',
  phone: saved.phone ?? '',
  line1: saved.line1 ?? '',
  line2: saved.line2 ?? '',
  city: saved.city,
  state: saved.state ?? '',
  postalCode: saved.postalCode ?? '',
  countryCode: saved.countryCode,
});

function SavedSummary({ address, onEdit }: { address: SavedAddress; onEdit: () => void }) {
  const lines = [
    address.companyName,
    address.line1,
    address.line2,
    [address.city, address.state, address.postalCode].filter(Boolean).join(', '),
  ].filter((line): line is string => typeof line === 'string' && line.length > 0);
  return (
    <div className="rounded-lg bg-surface-muted p-4">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0">
          <p className="flex items-center gap-2 text-small font-semibold text-foreground">
            {address.contactName}
            {address.isDefaultSender === true ? <span className="rounded-pill bg-primary-soft px-2 py-0.5 text-[11px] font-semibold text-primary">Default sender</span> : null}
          </p>
          <address className="mt-1 text-small not-italic leading-6 text-muted-foreground">
            {lines.map((line) => (
              <span key={line} className="block truncate">
                {line}
              </span>
            ))}
            <span className="block">
              <span aria-hidden="true">{flagEmoji(address.countryCode)} </span>
              {countryName(address.countryCode)}
            </span>
            {address.phone ? <span className="mt-1 block text-caption">{address.phone}</span> : null}
          </address>
        </div>
        <Button type="button" variant="secondary" size="sm" onClick={onEdit}>
          <Pencil className="h-3.5 w-3.5" aria-hidden="true" />
          Edit details
        </Button>
      </div>
    </div>
  );
}

function AddressCard({
  scope,
  title,
  icon: Icon,
  value,
  addresses,
  errors,
  onChange,
}: {
  scope: 'sender' | 'recipient';
  title: string;
  icon: LucideIcon;
  value: AddressDraft;
  addresses: SavedAddress[];
  errors: Record<string, string>;
  onChange: (next: AddressDraft) => void;
}) {
  const scoped = unprefix(scope, errors);
  const saved = value.mode === 'saved' ? addresses.find((address) => address.id === value.addressId) : undefined;
  const pickerId = `${scope}-book`;
  return (
    <section className="rounded-xl border border-border bg-surface p-5 shadow-xs md:p-6" aria-labelledby={`${scope}-title`}>
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-3">
          <span className="grid h-9 w-9 place-items-center rounded-lg bg-primary-soft text-primary">
            <Icon className="h-[18px] w-[18px]" aria-hidden="true" />
          </span>
          <h3 id={`${scope}-title`} className="font-display text-h3 font-bold">
            {title}
          </h3>
        </div>
        <Segmented<'saved' | 'new'>
          size="sm"
          label={`${title} address source`}
          value={value.mode}
          onChange={(mode) => onChange({ ...value, mode })}
          options={[
            { value: 'saved', label: 'Saved address' },
            { value: 'new', label: 'New address' },
          ]}
        />
      </div>
      <div className="mt-5 grid gap-4">
        {value.mode === 'saved' ? (
          <>
            <div className="grid gap-1.5">
              <label htmlFor={pickerId} className="text-small font-semibold">
                Address book
              </label>
              <AddressPicker
                id={pickerId}
                addresses={addresses}
                value={value.addressId}
                invalid={scoped.addressId !== undefined}
                describedBy={describedBy(pickerId, undefined, scoped.addressId)}
                onChange={(address) => onChange({ ...value, mode: 'saved', addressId: address.id })}
              />
              {scoped.addressId === undefined ? null : <FieldError id={`${pickerId}-error`}>{scoped.addressId}</FieldError>}
            </div>
            {saved === undefined ? null : <SavedSummary address={saved} onEdit={() => onChange(fromSaved(saved))} />}
          </>
        ) : (
          <AddressFields idPrefix={scope} value={value} errors={scoped} onChange={(patch) => onChange({ ...value, ...patch })} />
        )}
      </div>
    </section>
  );
}

export function AddressStep({
  draft,
  addresses,
  errors,
  onEdit,
}: {
  draft: ShipmentDraft;
  addresses: SavedAddress[];
  errors: Record<string, string>;
  onEdit: (draft: ShipmentDraft) => void;
}) {
  const [swapTurns, setSwapTurns] = useState(0);
  const senderOptions = addresses.filter((address) => address.id.length > 0);
  const swap = () => {
    setSwapTurns((turns) => turns + 1);
    onEdit({ ...draft, sender: draft.recipient, recipient: draft.sender });
  };
  return (
    <div className="grid">
      <AddressCard scope="sender" title="From" icon={PackageOpen} value={draft.sender} addresses={senderOptions} errors={errors} onChange={(sender) => onEdit({ ...draft, sender })} />
      {/* Swap button sits on the seam between the two cards */}
      <div className="relative z-10 -my-2 flex justify-center">
        <button
          type="button"
          onClick={swap}
          aria-label="Swap sender and recipient"
          className="grid h-10 w-10 place-items-center rounded-full border border-border bg-surface text-muted-foreground shadow-md transition-colors hover:border-primary/40 hover:text-primary"
        >
          <span className="grid place-items-center transition-transform duration-280 ease-brand" style={{ transform: `rotate(${swapTurns * 180}deg)` }}>
            <ArrowUpDown className="h-4 w-4" aria-hidden="true" />
          </span>
        </button>
      </div>
      <AddressCard scope="recipient" title="To" icon={MapPin} value={draft.recipient} addresses={addresses} errors={errors} onChange={(recipient) => onEdit({ ...draft, recipient })} />
    </div>
  );
}
