/**
 * VendorCustomers — /vendor/customers page feature.
 * Lists vendor-scoped customers with per-customer LTV (display name only).
 */

'use client';

import type { DehydratedState } from '@tanstack/react-query';
import { useState, type SubmitEvent } from 'react';
import { useQuery } from '@tanstack/react-query';
import { QueryBoundary } from '@platform-modules/ui-primitives';
import { HydratedIsland } from '@/components/HydratedIsland';
import { VendorShell } from '@/components/ui/layout/VendorShell';
import { Table } from '@/components/ui/primitives/Table';
import { Button } from '@/components/ui/primitives/Button';
import { Input } from '@/components/ui/primitives/Input';
import { Pagination } from '@/components/ui/primitives/Pagination';
import { EmptyState } from '@/components/ui/feedback/EmptyState';
import { LabelWithTooltip } from '@/components/ui/primitives/LabelWithTooltip';
import { useT, useLocale } from '@/lib/i18n/react';
import { formatDate, formatInteger } from '@/lib/format';
import { formatAgorotCurrencyILS } from '@/lib/money';
import { TableSkeleton } from '@/components/ui/feedback/Skeleton';
import type { DashboardPrefetchDescriptor } from '@/lib/query/prefetch-registry';

// ─── Types ────────────────────────────────────────────────────────────────────

interface VendorCustomerRow {
  userId: string;
  displayName: string | null;
  netAgorot: number;
  orderCount: number;
  lastAt: string | null;
}

interface VendorCustomersResponse {
  ok: boolean;
  data: {
    customers: VendorCustomerRow[];
    total: number;
    page: number;
    pageSize: number;
  };
}

const PAGE_SIZE = 50;

// ─── Hook ─────────────────────────────────────────────────────────────────────

function useVendorCustomers(search: string, page: number) {
  return useQuery({
    queryKey: vendorCustomersQueryKey(search, page),
    queryFn: () => fetchVendorCustomers(search, page),
    staleTime: 60_000,
  });
}

export function vendorCustomersQueryKey(search: string, page: number) {
  return ['vendor-customers', search, page] as const;
}

export async function fetchVendorCustomers(search: string, page: number) {
  const params = new URLSearchParams({
    page: String(page),
    pageSize: String(PAGE_SIZE),
  });
  if (search.trim()) params.set('search', search.trim());
  const res = await fetch(`/api/vendor/customers?${params.toString()}`);
  if (!res.ok) throw new Error('Failed to load customers');
  const json = (await res.json()) as VendorCustomersResponse;
  if (!json.ok) throw new Error('Failed to load customers');
  return json.data;
}

export const VENDOR_CUSTOMERS_PREFETCH_DESCRIPTOR: DashboardPrefetchDescriptor = {
  href: '/vendor/customers',
  queryKey: vendorCustomersQueryKey('', 1),
  queryFn: () => fetchVendorCustomers('', 1),
  staleTime: 60_000,
};

function VendorCustomersSkeleton() {
  return (
    <div
      className="flex flex-col gap-6"
      aria-hidden="true"
      data-testid="instant-skeleton:vendor-customers"
    >
      <TableSkeleton rows={5} cols={4} />
    </div>
  );
}

// ─── Inner ────────────────────────────────────────────────────────────────────

function VendorCustomersInner() {
  const t = useT('vendor_customers');
  const { locale } = useLocale();
  const [searchInput, setSearchInput] = useState('');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);
  const customersQuery = useVendorCustomers(search, page);

  const total = customersQuery.data?.total ?? 0;
  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));

  function handleSearchSubmit(e: SubmitEvent<HTMLFormElement>) {
    e.preventDefault();
    setSearch(searchInput);
    setPage(1);
  }

  return (
    <VendorShell variant="dashboard" currentPath="/vendor/customers">
      <div className="flex flex-col gap-6 p-4 lg:p-6">
        <form onSubmit={handleSearchSubmit} className="flex max-w-md gap-2">
          <Input
            type="search"
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            placeholder={t('search_placeholder')}
            aria-label={t('search_placeholder')}
          />
          <Button type="submit" variant="secondary" size="sm">
            {t('search_action')}
          </Button>
        </form>

        <QueryBoundary
          query={customersQuery}
          skeleton={<VendorCustomersSkeleton />}
          errorFallback={() => (
            <EmptyState
              title={t('error_title')}
              description={t('error_desc')}
              action={
                <Button variant="primary" size="sm" onClick={() => void customersQuery.refetch()}>
                  {t('retry')}
                </Button>
              }
            />
          )}
        >
          {(data) =>
            data.customers.length === 0 ? (
              <EmptyState title={t('empty_title')} description={t('empty_description')} />
            ) : (
              <section aria-label={t('table_label')} data-testid="instant-content:vendor-customers">
                <p className="text-text-muted mb-3 text-sm">{t('sort_caption')}</p>
                <div className="bg-surface-raised border-border-default overflow-hidden rounded-lg border">
                  <Table>
                    <Table.Head className="bg-surface-inset">
                      <Table.Row>
                        <Table.HeadCell className="text-text-secondary px-4 py-3 font-medium">
                          {t('col_name')}
                        </Table.HeadCell>
                        <Table.HeadCell className="text-text-secondary px-4 py-3 text-end font-medium">
                          <span className="inline-flex justify-end">
                            <LabelWithTooltip
                              label={t('col_net_spent')}
                              tooltip={t('col_spend_tooltip')}
                            />
                          </span>
                        </Table.HeadCell>
                        <Table.HeadCell className="text-text-secondary px-4 py-3 text-end font-medium">
                          <span className="inline-flex justify-end">
                            <LabelWithTooltip
                              label={t('col_orders')}
                              tooltip={t('col_orders_tooltip')}
                            />
                          </span>
                        </Table.HeadCell>
                        <Table.HeadCell className="text-text-secondary px-4 py-3 font-medium">
                          {t('col_last_purchase')}
                        </Table.HeadCell>
                      </Table.Row>
                    </Table.Head>
                    <Table.Body>
                      {data.customers.map((row) => (
                        <Table.Row
                          key={row.userId}
                          data-vendor-customer-row={row.userId}
                          className="hover:bg-surface-inset/50 duration-fast transition-colors"
                        >
                          <Table.Cell className="text-text-primary px-4 py-3 font-medium">
                            {row.displayName ?? t('guest_name')}
                          </Table.Cell>
                          <Table.Cell
                            className="text-text-primary px-4 py-3 text-end tabular-nums"
                            data-customer-net-agorot={row.netAgorot}
                          >
                            {formatAgorotCurrencyILS(row.netAgorot)}
                          </Table.Cell>
                          <Table.Cell className="text-text-primary px-4 py-3 text-end tabular-nums">
                            {formatInteger(row.orderCount, locale)}
                          </Table.Cell>
                          <Table.Cell className="text-text-primary px-4 py-3">
                            {row.lastAt ? formatDate(row.lastAt, locale) : t('no_last_purchase')}
                          </Table.Cell>
                        </Table.Row>
                      ))}
                    </Table.Body>
                  </Table>
                </div>
                <div className="mt-4">
                  <Pagination
                    page={page}
                    totalPages={totalPages}
                    onPageChange={setPage}
                    isLoading={customersQuery.isFetching}
                  />
                </div>
              </section>
            )
          }
        </QueryBoundary>
      </div>
    </VendorShell>
  );
}

// ─── Export ───────────────────────────────────────────────────────────────────

export interface VendorCustomersProps {
  dehydratedState?: DehydratedState;
}

export function VendorCustomers({ dehydratedState }: VendorCustomersProps) {
  return (
    <HydratedIsland dehydratedState={dehydratedState}>
      <VendorCustomersInner />
    </HydratedIsland>
  );
}
