'use client';

import { useMemo, useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Pencil, Plus, Search, Star, Trash2 } from 'lucide-react';
import { toast } from 'sonner';

import { AddressFormModal, type SavedAddress } from '@/components/addresses/address-form-modal';
import { EmptyBoxIllustration, NoResultsIllustration } from '@/components/illustrations';
import { PageHeader } from '@/components/layout/page-header';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Input } from '@/components/ui/input';
import { Menu, type MenuItem } from '@/components/ui/menu';
import { Pagination } from '@/components/ui/pagination';
import { Segmented } from '@/components/ui/segmented';
import { EmptyState, ErrorState, ForbiddenState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip } from '@/components/ui/tooltip';
import { ApiError, api, apiEnvelope } from '@/lib/api-client';
import { countryName, flagEmoji } from '@/lib/format';
import { usePermission } from '@/hooks/use-permission';
import { queryKeys } from '@/lib/query-keys';
import { cn } from '@/lib/utils';
import { ADDRESS_TYPES, type AddressType } from '@/shared/enums';

interface AddressPage {
  data: SavedAddress[];
  meta: { page: number; pageSize: number; total: number; totalPages: number };
}

export default function AddressesPage() {
  const canRead = usePermission('addresses:read');
  const canManage = usePermission('addresses:manage');
  const queryClient = useQueryClient();
  const [q, setQ] = useState('');
  const [type, setType] = useState<AddressType | ''>('');
  const [page, setPage] = useState(1);
  const [editor, setEditor] = useState<SavedAddress | null | undefined>(undefined);
  const [deleteTarget, setDeleteTarget] = useState<SavedAddress | null>(null);
  const [deleteError, setDeleteError] = useState<string | null>(null);
  const [deleting, setDeleting] = useState(false);

  const query = useMemo(() => {
    const params = new URLSearchParams({ page: String(page), pageSize: '20' });
    if (q.trim().length > 0) params.set('q', q.trim());
    if (type.length > 0) params.set('type', type);
    return `?${params.toString()}`;
  }, [page, q, type]);

  const list = useQuery({
    queryKey: queryKeys.addresses(query),
    enabled: canRead,
    queryFn: () => apiEnvelope<AddressPage>(`/addresses${query}`),
  });

  if (!canRead) return <ForbiddenState />;

  const rows = list.data?.data ?? [];
  const meta = list.data?.meta;
  const error = list.error instanceof ApiError ? list.error : null;
  const filtered = q.trim().length > 0 || type.length > 0;
  const emptyAll = !list.isLoading && error === null && rows.length === 0 && !filtered;
  const emptyFiltered = !list.isLoading && error === null && rows.length === 0 && filtered;

  const setDefault = (address: SavedAddress) => {
    void api(`/addresses/${address.id}/default-sender`, { method: 'POST' })
      .then(() => {
        toast.success('Default sender updated.');
        void queryClient.invalidateQueries({ queryKey: ['addresses'] });
      })
      .catch((reason: unknown) => toast.error(reason instanceof ApiError ? reason.message : 'Could not update default sender.'));
  };

  const menuFor = (address: SavedAddress): MenuItem[] => [
    { label: 'Edit', icon: Pencil, onSelect: () => setEditor(address) },
    { label: 'Set as default sender', icon: Star, disabled: address.isDefaultSender, disabledReason: 'Already the default sender', onSelect: () => setDefault(address) },
    { type: 'divider' },
    {
      label: 'Delete',
      icon: Trash2,
      danger: true,
      onSelect: () => {
        setDeleteError(null);
        setDeleteTarget(address);
      },
    },
  ];

  const star = (address: SavedAddress) =>
    canManage ? (
      <Tooltip label={address.isDefaultSender ? 'Default sender' : 'Set as default sender'}>
        <button
          type="button"
          aria-pressed={address.isDefaultSender}
          aria-label={address.isDefaultSender ? `${address.label ?? address.contactName} is the default sender` : `Set ${address.label ?? address.contactName} as default sender`}
          onClick={() => {
            if (!address.isDefaultSender) setDefault(address);
          }}
          className="grid h-8 w-8 place-items-center rounded-md transition-colors hover:bg-warning-soft"
        >
          <Star className={cn('h-4 w-4 transition-colors', address.isDefaultSender ? 'fill-warning text-warning' : 'text-subtle-foreground')} aria-hidden="true" />
        </button>
      </Tooltip>
    ) : address.isDefaultSender ? (
      <Star className="h-4 w-4 fill-warning text-warning" aria-label="Default sender" />
    ) : null;

  const fullAddress = (address: SavedAddress) =>
    [address.line1, address.line2, address.city, address.state, address.postalCode, countryName(address.countryCode)].filter(Boolean).join(', ');

  return (
    <div className="grid gap-5">
      <PageHeader
        title="Address book"
        description={meta === undefined ? 'Saved senders and recipients' : `${meta.total.toLocaleString()} address${meta.total === 1 ? '' : 'es'}`}
        actions={
          canManage ? (
            <Button type="button" onClick={() => setEditor(null)}>
              <Plus className="h-4 w-4" aria-hidden="true" />
              Add address
            </Button>
          ) : undefined
        }
      />

      <Card className="flex flex-col gap-3 p-3 sm:flex-row sm:items-center">
        <div className="min-w-0 flex-1">
          <Input
            type="search"
            aria-label="Search addresses"
            leading={<Search />}
            value={q}
            placeholder="Search label, name or city"
            onChange={(event) => {
              setQ(event.target.value);
              setPage(1);
            }}
          />
        </div>
        <Segmented<AddressType | ''>
          label="Address type"
          value={type}
          onChange={(value) => {
            setType(value);
            setPage(1);
          }}
          options={[
            { value: '', label: 'All' },
            ...ADDRESS_TYPES.map((value) => ({ value, label: value === 'BOTH' ? 'Both' : value === 'SENDER' ? 'Sender' : 'Recipient' })),
          ]}
          className="h-11 items-center self-start sm:self-auto"
        />
      </Card>

      {list.isLoading ? (
        <Card className="overflow-hidden p-0">
          <div className="h-11 border-b border-border bg-surface-muted" />
          {Array.from({ length: 6 }, (_, index) => (
            <div key={index} className="flex h-16 items-center gap-6 border-b border-border px-5 last:border-b-0">
              <Skeleton className="h-4 w-28" />
              <Skeleton className="h-4 w-32" />
              <Skeleton className="h-4 flex-1" />
              <Skeleton className="hidden h-5 w-16 rounded-pill md:block" />
            </div>
          ))}
        </Card>
      ) : null}
      {error !== null ? (
        <Card>
          <ErrorState message={error.message} requestId={error.requestId} onRetry={() => void list.refetch()} />
        </Card>
      ) : null}
      {emptyAll ? (
        <Card>
          <EmptyState
            illustration={<EmptyBoxIllustration size={120} />}
            title="You have no saved addresses"
            description="A sender address is needed to create shipments."
            action={
              canManage ? (
                <Button type="button" onClick={() => setEditor(null)}>
                  <Plus className="h-4 w-4" aria-hidden="true" />
                  Add address
                </Button>
              ) : undefined
            }
          />
        </Card>
      ) : null}
      {emptyFiltered ? (
        <Card>
          <EmptyState
            illustration={<NoResultsIllustration size={120} />}
            title="No addresses match your search"
            action={
              <Button
                type="button"
                variant="secondary"
                onClick={() => {
                  setQ('');
                  setType('');
                  setPage(1);
                }}
              >
                Clear filters
              </Button>
            }
          />
        </Card>
      ) : null}

      {rows.length > 0 ? (
        <>
          {/* Mobile cards */}
          <div className="grid gap-3 md:hidden">
            {rows.map((address) => (
              <article key={address.id} className="rounded-lg border border-border bg-surface p-4 shadow-xs">
                <div className="flex items-start justify-between gap-2">
                  <div className="min-w-0">
                    <p className="truncate font-semibold">{address.label ?? address.contactName}</p>
                    <p className="truncate text-caption text-muted-foreground">
                      {address.contactName}
                      {address.companyName === undefined ? '' : ` · ${address.companyName}`}
                    </p>
                  </div>
                  <div className="-mr-2 -mt-1 flex shrink-0 items-center">
                    {star(address)}
                    {canManage ? <Menu items={menuFor(address)} label={`Actions for ${address.label ?? address.contactName}`} /> : null}
                  </div>
                </div>
                <p className="mt-2 text-small text-muted-foreground">
                  <span aria-hidden="true">{flagEmoji(address.countryCode)} </span>
                  {fullAddress(address)}
                </p>
                <div className="mt-3 flex items-center justify-between gap-2">
                  <span className="text-small tabular-nums text-muted-foreground">{address.phone}</span>
                  <TypeBadge type={address.type} />
                </div>
              </article>
            ))}
          </div>

          {/* Desktop table */}
          <Card className="hidden overflow-hidden p-0 md:block">
            <div className="overflow-x-auto">
              <table className="w-full min-w-[840px] text-left text-small">
                <thead>
                  <tr className="h-11 border-b border-border bg-surface-muted/80 text-caption font-semibold uppercase tracking-[0.08em] text-muted-foreground">
                    <th scope="col" className="pl-5 pr-3 font-semibold">Label</th>
                    <th scope="col" className="px-3 font-semibold">Contact</th>
                    <th scope="col" className="px-3 font-semibold">Address</th>
                    <th scope="col" className="px-3 font-semibold">Phone</th>
                    <th scope="col" className="px-3 font-semibold">Type</th>
                    <th scope="col" className="w-12 pr-3">
                      <span className="sr-only">Actions</span>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map((address) => (
                    <tr key={address.id} className="h-16 border-b border-border transition-colors last:border-b-0 hover:bg-surface-muted/60">
                      <td className="max-w-[220px] pl-3 pr-3">
                        <span className="flex items-center gap-1">
                          <span className="shrink-0">{star(address) ?? <span className="inline-block w-8" />}</span>
                          <span className="truncate font-semibold text-foreground">{address.label ?? <span className="font-normal text-subtle-foreground">—</span>}</span>
                        </span>
                      </td>
                      <td className="max-w-[200px] px-3">
                        <span className="block truncate font-medium text-foreground">{address.contactName}</span>
                        {address.companyName === undefined ? null : <span className="block truncate text-caption text-muted-foreground">{address.companyName}</span>}
                      </td>
                      <td className="max-w-[320px] px-3">
                        <span className="block truncate text-muted-foreground" title={fullAddress(address)}>
                          <span aria-hidden="true">{flagEmoji(address.countryCode)} </span>
                          {fullAddress(address)}
                        </span>
                      </td>
                      <td className="whitespace-nowrap px-3 tabular-nums text-muted-foreground">{address.phone}</td>
                      <td className="px-3">
                        <TypeBadge type={address.type} />
                      </td>
                      <td className="pr-3">{canManage ? <Menu items={menuFor(address)} label={`Actions for ${address.label ?? address.contactName}`} /> : null}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>

          {meta === undefined ? null : (
            <Pagination page={meta.page} totalPages={meta.totalPages} total={meta.total} pageSize={meta.pageSize} noun="addresses" onPage={setPage} />
          )}
        </>
      ) : null}

      <AddressFormModal
        open={editor !== undefined}
        {...(editor === null || editor === undefined ? {} : { address: editor })}
        onClose={() => setEditor(undefined)}
        onSaved={() => {
          void queryClient.invalidateQueries({ queryKey: ['addresses'] });
        }}
      />
      <ConfirmDialog
        open={deleteTarget !== null}
        title="Delete this address?"
        message="Existing shipments keep their own copy of this address."
        confirmLabel="Delete address"
        cancelLabel="Keep address"
        error={deleteError}
        loading={deleting}
        onClose={() => setDeleteTarget(null)}
        onConfirm={() => {
          if (deleteTarget === null) return;
          setDeleting(true);
          setDeleteError(null);
          void api(`/addresses/${deleteTarget.id}`, { method: 'DELETE' })
            .then(() => {
              toast.success('Address deleted.');
              setDeleteTarget(null);
              void queryClient.invalidateQueries({ queryKey: ['addresses'] });
            })
            .catch((reason: unknown) => {
              setDeleteError(reason instanceof ApiError ? reason.message : 'The address could not be deleted.');
            })
            .finally(() => setDeleting(false));
        }}
      />
    </div>
  );
}

function TypeBadge({ type }: { type: AddressType }) {
  const style = type === 'SENDER' ? 'bg-primary-soft text-primary' : type === 'RECIPIENT' ? 'bg-info-soft text-info' : 'bg-surface-muted text-muted-foreground';
  return <span className={cn('inline-flex rounded-pill px-2.5 py-0.5 text-caption font-semibold', style)}>{type === 'BOTH' ? 'Both' : type === 'SENDER' ? 'Sender' : 'Recipient'}</span>;
}
