'use client';

import { useT, useLocale } from '@/lib/i18n/react';
import { interpolate } from '@/lib/i18n/interpolate';
import { formatDateTime } from '@/lib/format';
import { StatusBadge } from '@/components/ui/domain/StatusBadge';
import { RETURN_STATUS_MAP } from '@/features/returns/ReturnTimeline';
import { Table } from '@/components/ui/primitives/Table';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/overlays/Tooltip';
import { cn } from '@/lib/cn';
import type { ReturnStatus } from '@/lib/enums/return-status';

export interface ReturnIndexRow {
  id: string;
  buyerId: string;
  status: string;
  reason: string;
  createdAt: string;
  vendorRespondBy: string | null;
  vendorName: string;
}

export interface ReturnsIndexProps {
  rows: ReturnIndexRow[];
  statusFilter: string | null;
  allStatuses: readonly ReturnStatus[];
  chipBasePath?: string;
}

function reasonLabel(t: ReturnType<typeof useT<'returns'>>, reason: string): string {
  const tr = t as (k: string) => string;
  const key = `reason_${reason}`;
  const translated = tr(key);
  return translated !== key ? translated : reason;
}

function statusLabel(t: ReturnType<typeof useT<'returns'>>, status: ReturnStatus): string {
  const tr = t as (k: string) => string;
  return tr(`status_${status}`);
}

function isRespondOverdue(row: ReturnIndexRow): boolean {
  if (row.status !== 'requested' || !row.vendorRespondBy) return false;
  return new Date(row.vendorRespondBy).getTime() < Date.now();
}

export function ReturnsIndex({
  rows,
  statusFilter,
  allStatuses,
  chipBasePath = '/admin/returns',
}: ReturnsIndexProps) {
  const t = useT('returns');
  const { locale } = useLocale();

  return (
    <TooltipProvider delayDuration={200}>
      <div className="mx-auto max-w-6xl px-4 py-8">
        <nav aria-label={t('filterByStatusAria')} className="mb-6 flex flex-wrap gap-2">
          <a
            href={chipBasePath}
            className={cn(
              'rounded-full border px-3 py-1 text-sm font-medium transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1',
              !statusFilter
                ? 'border-brand-primary-600 bg-brand-primary-600 text-text-inverse'
                : 'bg-surface-base text-text-secondary border-border-default hover:bg-surface-raised',
            )}
            aria-current={!statusFilter ? 'page' : undefined}
          >
            {t('colAll')}
          </a>
          {allStatuses.map((s) => (
            <a
              key={s}
              href={`${chipBasePath}?status=${s}`}
              className={cn(
                'rounded-full border px-3 py-1 text-sm font-medium transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1',
                statusFilter === s
                  ? 'border-brand-primary-600 bg-brand-primary-600 text-text-inverse'
                  : 'bg-surface-base text-text-secondary border-border-default hover:bg-surface-raised',
              )}
              aria-current={statusFilter === s ? 'page' : undefined}
            >
              {statusLabel(t, s)}
            </a>
          ))}
        </nav>

        {rows.length === 0 ? (
          <p className="text-text-muted py-12 text-center">
            {statusFilter ? (
              <>
                {interpolate(t('emptyAdminFiltered'), {
                  status: statusLabel(t, statusFilter as ReturnStatus),
                })}{' '}
                <a
                  href={chipBasePath}
                  className="text-brand-primary-600 hover:text-brand-primary-800 underline-offset-2 hover:underline"
                >
                  {t('emptyAdminShowAll')}
                </a>
              </>
            ) : (
              t('emptyAdmin')
            )}
          </p>
        ) : (
          <Table className="border-border-default bg-surface-base rounded-lg border">
            <Table.Head className="bg-surface-raised border-border-default border-b">
              <Table.Row>
                <Table.HeadCell className="text-text-secondary px-4 py-3 font-medium">
                  {t('colId')}
                </Table.HeadCell>
                <Table.HeadCell className="text-text-secondary px-4 py-3 font-medium">
                  {t('colVendor')}
                </Table.HeadCell>
                <Table.HeadCell className="text-text-secondary px-4 py-3 font-medium">
                  {t('colBuyer')}
                </Table.HeadCell>
                <Table.HeadCell className="text-text-secondary px-4 py-3 font-medium">
                  {t('colStatus')}
                </Table.HeadCell>
                <Table.HeadCell className="text-text-secondary px-4 py-3 font-medium">
                  {t('colReason')}
                </Table.HeadCell>
                <Table.HeadCell className="text-text-secondary px-4 py-3 font-medium">
                  {t('colCreated')}
                </Table.HeadCell>
                <Table.HeadCell className="text-text-secondary px-4 py-3 font-medium">
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <span className="cursor-help underline decoration-dotted underline-offset-2">
                        {t('colRespondBy')}
                      </span>
                    </TooltipTrigger>
                    <TooltipContent side="top" className="max-w-xs text-wrap">
                      {t('colRespondByTooltip')}
                    </TooltipContent>
                  </Tooltip>
                </Table.HeadCell>
              </Table.Row>
            </Table.Head>
            <Table.Body>
              {rows.map((row) => {
                const overdue = isRespondOverdue(row);
                const href = `/admin/returns/${row.id}`;
                return (
                  <Table.Row
                    key={row.id}
                    className="hover:bg-surface-raised cursor-pointer transition-colors"
                    onClick={(e) => {
                      if (
                        (e.target as HTMLElement).closest(
                          'a, button, input, label, select, [role="checkbox"], [role="button"]',
                        )
                      ) {
                        return;
                      }
                      window.location.assign(href);
                    }}
                  >
                    <Table.Cell className="text-text-secondary px-4 py-3 font-mono text-xs">
                      <a
                        href={href}
                        className="text-text-primary font-medium hover:underline focus-visible:outline-none"
                      >
                        {row.id.slice(0, 8)}…
                      </a>
                    </Table.Cell>
                    <Table.Cell className="text-text-primary max-w-[12rem] truncate px-4 py-3">
                      {row.vendorName}
                    </Table.Cell>
                    <Table.Cell className="text-text-muted px-4 py-3 font-mono text-xs">
                      <a
                        href={`/admin/users/${row.buyerId}`}
                        className="hover:text-text-primary hover:underline"
                        title={row.buyerId}
                        onClick={(e) => e.stopPropagation()}
                      >
                        {row.buyerId.slice(0, 8)}…
                      </a>
                    </Table.Cell>
                    <Table.Cell className="px-4 py-3">
                      <StatusBadge
                        state={row.status as ReturnStatus}
                        map={RETURN_STATUS_MAP}
                        ns="returns"
                        size="sm"
                      />
                    </Table.Cell>
                    <Table.Cell className="text-text-secondary px-4 py-3">
                      {reasonLabel(t, row.reason)}
                    </Table.Cell>
                    <Table.Cell className="text-text-muted px-4 py-3 whitespace-nowrap">
                      {formatDateTime(row.createdAt, locale)}
                    </Table.Cell>
                    <Table.Cell
                      className={cn(
                        'text-text-muted px-4 py-3 whitespace-nowrap',
                        overdue && 'text-danger-600 font-medium',
                      )}
                    >
                      {row.vendorRespondBy ? (
                        <>
                          {formatDateTime(row.vendorRespondBy, locale)}
                          {overdue ? (
                            <span className="ms-1 text-xs">({t('respondOverdue')})</span>
                          ) : null}
                        </>
                      ) : (
                        '—'
                      )}
                    </Table.Cell>
                  </Table.Row>
                );
              })}
            </Table.Body>
          </Table>
        )}

        {rows.length > 0 && (
          <p className="text-text-muted mt-3 text-end text-xs">
            {rows.length === 200
              ? t('countResultsCapped')
              : interpolate(t('countResultsExact'), { count: rows.length })}
          </p>
        )}
      </div>
    </TooltipProvider>
  );
}
