'use client';

import { BookUser, Star, X } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';

import { AddressFields } from '@/components/shipments/address-fields';
import { FormAlert, FormField } from '@/components/forms/form-field';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Drawer } from '@/components/ui/overlay';
import { Segmented } from '@/components/ui/segmented';
import { Switch } from '@/components/ui/switch';
import { ApiError, api } from '@/lib/api-client';
import { addressIssues, addressPayload, emptyAddress, type AddressDraft } from '@/lib/wizard';
import { ADDRESS_TYPES, type AddressType } from '@/shared/enums';

export interface SavedAddress {
  id: string;
  type: AddressType;
  label?: string;
  contactName: string;
  companyName?: string;
  email?: string;
  phone: string;
  line1: string;
  line2?: string;
  city: string;
  state?: string;
  postalCode: string;
  countryCode: string;
  isDefaultSender: boolean;
}

const toDraft = (address?: SavedAddress): AddressDraft => {
  if (address === undefined) return { ...emptyAddress(), saveToBook: true };
  return {
    mode: 'new',
    addressId: address.id,
    saveToBook: true,
    contactName: address.contactName,
    companyName: address.companyName ?? '',
    email: address.email ?? '',
    phone: address.phone,
    line1: address.line1,
    line2: address.line2 ?? '',
    city: address.city,
    state: address.state ?? '',
    postalCode: address.postalCode,
    countryCode: address.countryCode,
  };
};

function AddressFormBody({
  address,
  onClose,
  onSaved,
}: {
  address?: SavedAddress;
  onClose: () => void;
  onSaved: () => void;
}) {
  const [fields, setFields] = useState<AddressDraft>(() => toDraft(address));
  const [label, setLabel] = useState(address?.label ?? '');
  const [type, setType] = useState<AddressType>(address?.type ?? 'BOTH');
  const [isDefaultSender, setIsDefaultSender] = useState(address?.isDefaultSender ?? false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [pending, setPending] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);

  return (
    <form
      className="flex h-full flex-col"
      noValidate
      onSubmit={(event) => {
        event.preventDefault();
        const nextErrors = addressIssues({ ...fields, mode: 'new' });
        if (Object.keys(nextErrors).length > 0) {
          setErrors(nextErrors);
          return;
        }
        setPending(true);
        setFormError(null);
        const payload = {
          ...addressPayload(fields),
          type,
          ...(label.trim().length === 0 ? {} : { label: label.trim() }),
          isDefaultSender,
        };
        const request =
          address === undefined
            ? api<SavedAddress>('/addresses', { json: payload })
            : api<SavedAddress>(`/addresses/${address.id}`, { method: 'PATCH', json: payload });
        void request
          .then(() => {
            toast.success(address === undefined ? 'Address saved.' : 'Address updated.');
            onSaved();
            onClose();
          })
          .catch((error: unknown) => {
            setFormError(error instanceof ApiError ? error.message : 'The address could not be saved.');
          })
          .finally(() => setPending(false));
      }}
    >
      <div className="min-h-0 flex-1 overflow-y-auto px-5 py-5 md:px-6">
        <div className="grid gap-4">
          <div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-end">
            <FormField id="address-label" label="Label (optional)" hint="For example Main warehouse">
              <Input id="address-label" value={label} aria-describedby="address-label-hint" onChange={(event) => setLabel(event.target.value)} />
            </FormField>
            <div className="grid gap-1.5 sm:pb-[22px]">
              <span className="text-small font-semibold" id="address-type-label">
                Type
              </span>
              <Segmented<AddressType>
                label="Address type"
                value={type}
                onChange={setType}
                options={ADDRESS_TYPES.map((value) => ({ value, label: value === 'BOTH' ? 'Both' : value === 'SENDER' ? 'Sender' : 'Recipient' }))}
                className="h-11 items-center"
              />
            </div>
          </div>
          <div className="h-px bg-border" aria-hidden="true" />
          <AddressFields idPrefix="book" value={fields} errors={errors} showSaveOption={false} onChange={(patch) => setFields((current) => ({ ...current, ...patch, saveToBook: true }))} />
          <label className="flex cursor-pointer items-center justify-between gap-4 rounded-lg border border-border bg-surface-muted/50 px-4 py-3">
            <span>
              <span className="flex items-center gap-1.5 text-small font-semibold">
                <Star className="h-4 w-4 text-warning" aria-hidden="true" />
                Make this my default sender
              </span>
              <span className="mt-0.5 block text-caption text-muted-foreground">Preselected as the From address in new shipments.</span>
            </span>
            <Switch checked={isDefaultSender} onCheckedChange={setIsDefaultSender} label="Make this my default sender" />
          </label>
          {formError === null ? null : <FormAlert>{formError}</FormAlert>}
        </div>
      </div>
      <div className="flex shrink-0 justify-end gap-2 border-t border-border bg-surface px-5 py-4 md:px-6">
        <Button type="button" variant="secondary" onClick={onClose}>
          Cancel
        </Button>
        <Button type="submit" loading={pending}>
          Save address
        </Button>
      </div>
    </form>
  );
}

export function AddressFormModal({
  open,
  address,
  onClose,
  onSaved,
}: {
  open: boolean;
  address?: SavedAddress;
  onClose: () => void;
  onSaved: () => void;
}) {
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const media = window.matchMedia('(max-width: 767px)');
    const update = () => setIsMobile(media.matches);
    update();
    media.addEventListener('change', update);
    return () => media.removeEventListener('change', update);
  }, []);

  if (!open) return null;

  const formKey = address?.id ?? 'new';
  const title = address === undefined ? 'Add address' : 'Edit address';

  return (
    <Drawer open title={title} side={isMobile ? 'bottom' : 'right'} onClose={onClose} className={isMobile ? 'flex h-[100dvh] max-h-[100dvh] flex-col rounded-none p-0 pt-3' : 'flex flex-col p-0'}>
      <div className="flex shrink-0 items-center justify-between gap-3 border-b border-border px-5 py-4 md:px-6">
        <div className="flex items-center gap-3">
          <span className="grid h-9 w-9 place-items-center rounded-lg bg-primary-soft text-primary">
            <BookUser className="h-[18px] w-[18px]" aria-hidden="true" />
          </span>
          <div>
            <h2 className="font-display text-h3 font-bold">{title}</h2>
            <p className="text-caption text-muted-foreground">{address === undefined ? 'Save a sender or recipient for faster shipping.' : 'Changes apply to future shipments only.'}</p>
          </div>
        </div>
        <button type="button" aria-label="Close" onClick={onClose} className="grid h-9 w-9 place-items-center rounded-md text-muted-foreground hover:bg-surface-muted hover:text-foreground">
          <X className="h-4 w-4" aria-hidden="true" />
        </button>
      </div>
      <div className="min-h-0 flex-1">
        <AddressFormBody key={formKey} address={address} onClose={onClose} onSaved={onSaved} />
      </div>
    </Drawer>
  );
}
