'use client';

import { useCallback, useState } from 'react';
import { HydratedIsland } from '@/components/HydratedIsland';
import { VendorShell } from '@/components/ui/layout/VendorShell';
import { useT } from '@/lib/i18n/react';
import { formatDateTime } from '@/lib/format';
import type { Locale } from '@/lib/i18n/index';
import { Button } from '@/components/ui/primitives/Button';
import { Table } from '@/components/ui/primitives/Table';
import { LabelWithTooltip } from '@/components/ui/primitives/LabelWithTooltip';
import { Badge } from '@/components/ui/primitives/Badge';
import { captureCaught } from '@/lib/observability';
import { PersonalDealActions, type PersonalDealSeed } from './PersonalDealActions';

export interface PersonalDealPageRow {
  requestId: string;
  status: 'PENDING' | 'ACCEPTED' | 'REJECTED' | 'EXPIRED';
  responseDeadline: string | null;
  customerDisplay: string;
  sourceDealTitle: string;
  seed: PersonalDealSeed;
}

export interface VendorPersonalDealsPageProps {
  rows: PersonalDealPageRow[];
  locale: string;
}

function formatCustomerDisplay(
  display: string,
  t: ReturnType<typeof useT<'vendor_personal_deals'>>,
): { text: string; masked: boolean } {
  if (display === '—') {
    return { text: t('customer_unknown'), masked: false };
  }
  const phoneMatch = display.match(/^(?:XXX-XXXX-)?(\d{3})$/);
  if (phoneMatch) {
    return { text: t('customer_masked').replace('{hint}', phoneMatch[1]!), masked: true };
  }
  if (!display.includes(' ') && !/[\u0590-\u05FF]/.test(display) && display.length <= 24) {
    return { text: t('customer_masked').replace('{hint}', display.slice(-4)), masked: true };
  }
  return { text: display, masked: false };
}

function HeaderCell({ label, tooltip }: { label: string; tooltip?: string }) {
  if (!tooltip) {
    return <span>{label}</span>;
  }
  return <LabelWithTooltip label={label} tooltip={tooltip} />;
}

function isDeadlineExpired(deadline: string | null): boolean {
  if (!deadline) return false;
  return new Date(deadline).getTime() < Date.now();
}

function statusLabel(
  status: PersonalDealPageRow['status'],
  t: ReturnType<typeof useT<'vendor_personal_deals'>>,
): string {
  switch (status) {
    case 'ACCEPTED':
      return t('status_ACCEPTED');
    case 'REJECTED':
      return t('status_REJECTED');
    case 'EXPIRED':
      return t('status_EXPIRED');
    default:
      return t('status_PENDING');
  }
}

function IdCell({
  requestId,
  t,
}: {
  requestId: string;
  t: ReturnType<typeof useT<'vendor_personal_deals'>>;
}) {
  const [copied, setCopied] = useState(false);
  const shortId = requestId.slice(0, 8);

  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(requestId);
      setCopied(true);
      window.setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      captureCaught(err, {
        scope: 'features.vendor-personal-deals.VendorPersonalDealsPage.copyId',
        severity: 'info',
      });
    }
  }, [requestId]);

  return (
    <Button
      type="button"
      variant="ghost"
      size="sm"
      className="hover:text-brand-primary-600 h-auto min-h-0 p-0 font-mono text-sm underline-offset-2 shadow-none hover:underline"
      title={t('col_id_tooltip')}
      onClick={() => void handleCopy()}
    >
      {copied ? t('col_id_copied') : shortId}
    </Button>
  );
}

export function VendorPersonalDealsPage({ rows, locale }: VendorPersonalDealsPageProps) {
  const t = useT('vendor_personal_deals');
  const [expandedRequestId, setExpandedRequestId] = useState<string | null>(null);
  return (
    <HydratedIsland>
      <VendorShell variant="dashboard" currentPath="/vendor/personal-deals">
        <div className="flex flex-col gap-4 p-4 lg:p-6">
          <h1 className="text-text-primary text-2xl font-bold">{t('page_title')}</h1>
          {rows.length === 0 ? (
            <p className="text-text-muted max-w-prose text-sm leading-relaxed">
              {t('empty_state')}
            </p>
          ) : (
            <Table className="border-border-subtle rounded-lg border">
              <Table.Head className="bg-surface-raised text-text-secondary">
                <Table.Row>
                  <Table.HeadCell className="px-4 py-3 font-semibold">
                    <HeaderCell label={t('col_id')} tooltip={t('col_id_tooltip')} />
                  </Table.HeadCell>
                  <Table.HeadCell className="px-4 py-3 font-semibold">
                    <HeaderCell label={t('col_customer')} tooltip={t('col_customer_tooltip')} />
                  </Table.HeadCell>
                  <Table.HeadCell className="px-4 py-3 font-semibold">
                    <HeaderCell
                      label={t('col_source_deal')}
                      tooltip={t('col_source_deal_tooltip')}
                    />
                  </Table.HeadCell>
                  <Table.HeadCell className="px-4 py-3 font-semibold">
                    <HeaderCell label={t('col_deadline')} tooltip={t('col_deadline_tooltip')} />
                  </Table.HeadCell>
                  <Table.HeadCell className="px-4 py-3 font-semibold">
                    {t('col_status')}
                  </Table.HeadCell>
                  <Table.HeadCell className="px-4 py-3 font-semibold">
                    {t('col_actions')}
                  </Table.HeadCell>
                </Table.Row>
              </Table.Head>
              <Table.Body>
                {rows.map((row) => {
                  const expired = isDeadlineExpired(row.responseDeadline);
                  const deadline = row.responseDeadline
                    ? formatDateTime(row.responseDeadline, locale as Locale)
                    : '—';
                  const customer = formatCustomerDisplay(row.customerDisplay, t);
                  return (
                    <Table.Row
                      key={row.requestId}
                      className="hover:bg-surface-raised transition-colors"
                    >
                      <Table.Cell className="px-4 py-3">
                        <IdCell requestId={row.requestId} t={t} />
                      </Table.Cell>
                      <Table.Cell className="text-text-secondary px-4 py-3">
                        <span title={customer.masked ? t('col_customer_tooltip') : undefined}>
                          {customer.text}
                        </span>
                      </Table.Cell>
                      <Table.Cell className="text-text-secondary px-4 py-3">
                        {row.sourceDealTitle}
                      </Table.Cell>
                      <Table.Cell className="text-text-secondary px-4 py-3">
                        <div className="flex flex-wrap items-center gap-2">
                          <span>{deadline}</span>
                          {expired && row.status === 'PENDING' && (
                            <Badge tone="warning" size="sm">
                              {t('deadline_expired')}
                            </Badge>
                          )}
                        </div>
                      </Table.Cell>
                      <Table.Cell className="px-4 py-3">
                        <Badge size="sm">{statusLabel(row.status, t)}</Badge>
                      </Table.Cell>
                      <Table.Cell className="px-4 py-3">
                        <div className="flex flex-col items-start gap-2">
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            aria-expanded={expandedRequestId === row.requestId}
                            aria-controls={`personal-deal-details-${row.requestId}`}
                            onClick={() =>
                              setExpandedRequestId((current) =>
                                current === row.requestId ? null : row.requestId,
                              )
                            }
                          >
                            {expandedRequestId === row.requestId
                              ? t('details_close')
                              : t('details_open')}
                          </Button>
                          {expandedRequestId === row.requestId && (
                            <section
                              id={`personal-deal-details-${row.requestId}`}
                              aria-label={`${t('details_title')} ${row.requestId.slice(0, 8)}`}
                              className="bg-surface-raised border-border-subtle flex min-w-56 flex-col gap-1 rounded-lg border p-3 text-sm"
                            >
                              <h2 className="text-text-primary font-semibold">
                                {t('details_title')}
                              </h2>
                              <p>{`${t('col_customer')}: ${customer.text}`}</p>
                              <p>{`${t('col_source_deal')}: ${row.sourceDealTitle}`}</p>
                              <p>{`${t('col_status')}: ${statusLabel(row.status, t)}`}</p>
                              <p>{`${t('details_price')}: ${row.seed.discountedPrice}`}</p>
                              <p>{`${t('details_quantity')}: ${row.seed.quantityTotal}`}</p>
                            </section>
                          )}
                          {row.status === 'PENDING' && (
                            <PersonalDealActions
                              requestId={row.requestId}
                              seed={row.seed}
                              disabled={expired}
                            />
                          )}
                        </div>
                      </Table.Cell>
                    </Table.Row>
                  );
                })}
              </Table.Body>
            </Table>
          )}
        </div>
      </VendorShell>
    </HydratedIsland>
  );
}
