'use client';

/**
 * VendorEarnings — DB-aggregated earnings table with summary cards + pagination.
 * Uses usePaginatedQuery (useState/useEffect, no React Query dependency).
 *
 * Props accept SSR-hydrated initialData/initialTotal/initialSummary so first
 * paint is instant even before the client-side refetch fires.
 */

import { useT, useLocale } from '@/lib/i18n/react';
import { usePaginatedQuery } from '@/lib/hooks/usePaginatedQuery';
import { Button } from '@/components/ui/primitives/Button';
import { IconButton } from '@/components/ui/primitives/IconButton';
import { Table } from '@/components/ui/primitives/Table';
import { Icon } from '@/components/ui/icons/Icon';
import { ErrorBoundary } from '@/components/ui/feedback/ErrorBoundary';
import { Spinner } from '@/components/ui/feedback/Spinner';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/overlays/Tooltip/Tooltip';
import { formatInteger } from '@/lib/format';
import { formatMonthYear } from '@/lib/datetime';
import { formatAgorotCurrencyILS } from '@/lib/money.js';
import { StatusBadge, type StatusEntry } from '@/components/ui/domain/StatusBadge/StatusBadge';
import type {
  VendorEarningsRow,
  VendorEarningsSummary,
} from '@/server/domain/vendor-earnings/queries.js';

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

export interface VendorEarningsProps {
  initialData: VendorEarningsRow[];
  initialTotal: number;
  initialSummary: VendorEarningsSummary;
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

const EARNINGS_STATUS_MAP: Record<VendorEarningsRow['status'], StatusEntry> = {
  pending: { tone: 'warning', labelKey: 'status_pending' },
  paid: { tone: 'success', labelKey: 'status_paid' },
  disputed: { tone: 'danger', labelKey: 'status_disputed' },
};

// ─── Summary Card ─────────────────────────────────────────────────────────────

interface SummaryCardProps {
  label: string;
  value: string;
}

function SummaryCard({ label, value }: SummaryCardProps) {
  return (
    <div className="bg-surface-raised border-border-default rounded-lg border p-4">
      <p className="text-text-secondary text-sm">{label}</p>
      <p className="text-text-primary mt-1 text-xl font-semibold">{value}</p>
    </div>
  );
}

// ─── Inner component (inside ErrorBoundary) ───────────────────────────────────

function VendorEarningsInner({ initialData, initialTotal, initialSummary }: VendorEarningsProps) {
  const t = useT('vendor_earnings');
  const tPagination = useT('pagination');
  const { locale } = useLocale();

  const { data, totalPages, page, isLoading, setPage, meta } = usePaginatedQuery<VendorEarningsRow>(
    {
      endpoint: '/api/vendor/earnings',
      dataKey: 'data',
      limit: 12,
      initialData,
      initialTotal,
      includeEnvelopeMeta: true,
    },
  );

  const summary = (meta?.summary as VendorEarningsSummary | undefined) ?? initialSummary;

  return (
    <div className="space-y-6">
      {/* Summary cards */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
        <SummaryCard
          label={t('summary_total')}
          value={formatAgorotCurrencyILS(summary.totalVendorAgorot)}
        />
        <SummaryCard
          label={t('summary_current_month')}
          value={formatAgorotCurrencyILS(summary.currentMonthVendorAgorot)}
        />
        <SummaryCard
          label={t('summary_pending')}
          value={formatAgorotCurrencyILS(summary.pendingVendorAgorot)}
        />
      </div>

      {/* Table */}
      <div className="bg-surface-raised border-border-default overflow-hidden rounded-lg border">
        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <Spinner size="md" />
          </div>
        ) : data.length === 0 ? (
          <div className="py-12 text-center">
            <p className="text-text-primary font-medium">{t('empty_title')}</p>
            <p className="text-text-secondary mt-1 text-sm">{t('empty_description')}</p>
            <Button variant="primary" size="sm" className="mt-4" asChild>
              <a href="/vendor/deals/new">{t('empty_cta')}</a>
            </Button>
          </div>
        ) : (
          <TooltipProvider>
            <Table>
              <Table.Head className="bg-surface-inset">
                <Table.Row>
                  <Table.HeadCell className="text-text-secondary px-4 py-3 font-medium">
                    {t('col_period')}
                  </Table.HeadCell>
                  <Table.HeadCell className="text-text-secondary px-4 py-3 text-end font-medium">
                    {t('col_purchases')}
                  </Table.HeadCell>
                  <Table.HeadCell className="text-text-secondary px-4 py-3 text-end font-medium">
                    {t('col_gross')}
                  </Table.HeadCell>
                  <Table.HeadCell className="text-text-secondary px-4 py-3 text-end font-medium">
                    <span className="inline-flex items-center justify-end gap-1">
                      {t('col_platform_fee')}
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <IconButton
                            variant="ghost"
                            size="sm"
                            shape="square"
                            className="text-text-muted hover:text-text-secondary focus-visible:outline-brand-primary-500 h-auto min-h-0 w-auto p-0 shadow-none"
                            aria-label={t('col_platform_fee_tooltip')}
                            icon={<Icon name="Info" size="xs" aria-hidden />}
                          />
                        </TooltipTrigger>
                        <TooltipContent>{t('col_platform_fee_tooltip')}</TooltipContent>
                      </Tooltip>
                    </span>
                  </Table.HeadCell>
                  <Table.HeadCell className="text-text-secondary px-4 py-3 text-end font-medium">
                    {t('col_net')}
                  </Table.HeadCell>
                  <Table.HeadCell className="text-text-secondary px-4 py-3 font-medium">
                    {t('col_status')}
                  </Table.HeadCell>
                </Table.Row>
              </Table.Head>
              <Table.Body>
                {data.map((row) => (
                  <Table.Row
                    key={row.periodMonth}
                    className="hover:bg-surface-inset/50 transition-colors duration-[var(--duration-fast)]"
                  >
                    <Table.Cell className="text-text-primary px-4 py-3 font-medium">
                      {formatMonthYear(`${row.periodMonth}-01`, locale)}
                    </Table.Cell>
                    <Table.Cell className="text-text-primary px-4 py-3 text-end">
                      {formatInteger(row.purchaseCount, locale)}
                    </Table.Cell>
                    <Table.Cell className="text-text-primary px-4 py-3 text-end">
                      {formatAgorotCurrencyILS(row.grossAgorot)}
                    </Table.Cell>
                    <Table.Cell className="text-text-secondary px-4 py-3 text-end">
                      {formatAgorotCurrencyILS(row.platformFeeAgorot)}
                    </Table.Cell>
                    <Table.Cell className="text-text-primary px-4 py-3 text-end font-medium">
                      {formatAgorotCurrencyILS(row.vendorAmountAgorot)}
                    </Table.Cell>
                    <Table.Cell className="px-4 py-3">
                      <StatusBadge
                        state={row.status}
                        map={EARNINGS_STATUS_MAP}
                        ns="vendor_earnings"
                      />
                    </Table.Cell>
                  </Table.Row>
                ))}
              </Table.Body>
            </Table>
          </TooltipProvider>
        )}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between">
          <Button variant="ghost" size="sm" onClick={() => setPage(page - 1)} disabled={page <= 1}>
            {tPagination('prevShort')}
          </Button>
          <span className="text-text-secondary text-sm">
            {page} / {totalPages}
          </span>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setPage(page + 1)}
            disabled={page >= totalPages}
          >
            {tPagination('nextShort')}
          </Button>
        </div>
      )}
    </div>
  );
}

// ─── Public export (wrapped in ErrorBoundary) ─────────────────────────────────

export function VendorEarnings(props: VendorEarningsProps) {
  return (
    <ErrorBoundary>
      <VendorEarningsInner {...props} />
    </ErrorBoundary>
  );
}
