'use client';

import { useState } from 'react';
import { useT, useLocale } from '@/lib/i18n/react';
import { formatDateTime } from '@/lib/format';
import { usePaginatedQuery } from '@/lib/hooks/usePaginatedQuery';
import { captureCaught } from '@/lib/observability';
import { HydratedIsland } from '@/components/HydratedIsland';
import type { Locale } from '@/lib/i18n';
import { Stack } from '@/components/ui/layout/Stack';
import { InlineNotice } from '@/components/ui/feedback/InlineNotice';
import { TableSkeleton } from '@/components/ui/feedback/Skeleton';
import { Button } from '@/components/ui/primitives/Button';
import { Pagination } from '@/components/ui/primitives/Pagination';
import { Table } from '@/components/ui/primitives/Table/Table';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogClose,
} from '@/components/ui/overlays/Dialog';

const PAGE_SIZE = 50;

interface MockEmailRow {
  id: string;
  created_at: string;
  to_addr: string;
  subject: string;
  tags: string;
}

export interface EmailLogTabProps {
  /** True when EMAIL_MOCK_DB is not bound (production or missing binding). */
  isProd: boolean;
  locale?: Locale;
  /** SSR-seeded first page (dev mock DB only). */
  initialEmails?: MockEmailRow[];
  initialTotal?: number;
}

function EmailLogTabProd() {
  const t = useT('admin_email_log');
  return <InlineNotice tone="info" description={t('prod_note')} />;
}

function EmailLogTabDev({
  initialEmails = [],
  initialTotal = 0,
}: Pick<EmailLogTabProps, 'initialEmails' | 'initialTotal'>) {
  const t = useT('admin_email_log');
  const { locale } = useLocale();
  const [previewId, setPreviewId] = useState<string | null>(null);

  const {
    data: emails,
    totalPages,
    page,
    isInitialLoading,
    error,
    setPage,
  } = usePaginatedQuery<MockEmailRow>({
    endpoint: '/api/admin/email-mock',
    limit: PAGE_SIZE,
    initialData: initialEmails,
    initialTotal,
    dataKey: 'emails',
  });

  return (
    <Stack gap="4">
      {isInitialLoading && <TableSkeleton rows={8} cols={5} />}
      {error && <InlineNotice tone="danger" description={t('load_error')} />}

      {!isInitialLoading && !error && emails.length === 0 && (
        <InlineNotice tone="info" description={t('empty')} />
      )}

      {emails.length > 0 && (
        <div className="rounded-md border border-[var(--color-border-default)]">
          <Table>
            <Table.Head className="bg-[var(--color-surface-inset)]">
              <Table.Row>
                <Table.HeadCell className="px-4 py-2 text-[var(--color-text-secondary)]">
                  {t('col_sent')}
                </Table.HeadCell>
                <Table.HeadCell className="px-4 py-2 text-[var(--color-text-secondary)]">
                  {t('col_to')}
                </Table.HeadCell>
                <Table.HeadCell className="px-4 py-2 text-[var(--color-text-secondary)]">
                  {t('col_subject')}
                </Table.HeadCell>
                <Table.HeadCell className="px-4 py-2 text-[var(--color-text-secondary)]">
                  {t('col_tags')}
                </Table.HeadCell>
                <Table.HeadCell className="sr-only px-4 py-2">{t('col_actions')}</Table.HeadCell>
              </Table.Row>
            </Table.Head>
            <Table.Body>
              {emails.map((row) => {
                let tags: Array<{ name: string; value: string }> = [];
                try {
                  const parsed = JSON.parse(row.tags);
                  if (Array.isArray(parsed)) tags = parsed;
                } catch (err) {
                  captureCaught(err, {
                    scope: 'features.admin-email-log.EmailLogTab',
                    severity: 'info',
                  });
                }
                const typeTag = tags.find((tg) => tg.name === 'type');
                return (
                  <Table.Row key={row.id} className="hover:bg-[var(--color-surface-inset)]">
                    <Table.Cell className="px-4 py-2 whitespace-nowrap text-[var(--color-text-secondary)]">
                      {formatDateTime(row.created_at, locale)}
                    </Table.Cell>
                    <Table.Cell className="px-4 py-2 font-mono text-xs text-[var(--color-text-primary)]">
                      {row.to_addr}
                    </Table.Cell>
                    <Table.Cell className="px-4 py-2 text-[var(--color-text-primary)]">
                      {row.subject}
                    </Table.Cell>
                    <Table.Cell className="px-4 py-2">
                      {typeTag && (
                        <span className="rounded bg-[var(--color-surface-inset)] px-1.5 py-0.5 text-xs text-[var(--color-text-secondary)]">
                          {typeTag.value}
                        </span>
                      )}
                    </Table.Cell>
                    <Table.Cell className="px-4 py-2">
                      <Button size="sm" variant="ghost" onClick={() => setPreviewId(row.id)}>
                        {t('preview_btn')}
                      </Button>
                    </Table.Cell>
                  </Table.Row>
                );
              })}
            </Table.Body>
          </Table>
        </div>
      )}

      {totalPages > 1 && <Pagination page={page} totalPages={totalPages} onPageChange={setPage} />}

      {previewId && (
        <Dialog
          open
          onOpenChange={(open) => {
            if (!open) setPreviewId(null);
          }}
        >
          <DialogContent className="max-w-3xl">
            <DialogHeader>
              <DialogTitle>{t('preview_title')}</DialogTitle>
              <DialogClose asChild>
                <Button variant="ghost" size="sm" className="ms-auto">
                  {t('preview_close')}
                </Button>
              </DialogClose>
            </DialogHeader>
            <iframe
              src={`/api/admin/email-mock/${previewId}`}
              className="h-(--email-log-panel-height) w-full rounded border border-[var(--color-border-default)]"
              sandbox="allow-same-origin"
              title={t('preview_title')}
            />
          </DialogContent>
        </Dialog>
      )}
    </Stack>
  );
}

function EmailLogTabInner({ isProd, initialEmails, initialTotal }: EmailLogTabProps) {
  if (isProd) return <EmailLogTabProd />;
  return <EmailLogTabDev initialEmails={initialEmails} initialTotal={initialTotal} />;
}

export function EmailLogTab({ isProd, locale, initialEmails, initialTotal }: EmailLogTabProps) {
  return (
    <HydratedIsland locale={locale}>
      <EmailLogTabInner isProd={isProd} initialEmails={initialEmails} initialTotal={initialTotal} />
    </HydratedIsland>
  );
}
