import Link from 'next/link';
import { DashboardShell } from '../../../../components/dashboard-shell';
import { WebhookRetryForm } from '../../../../components/webhook-retry-form';
import { requireAuthToken } from '../../../../lib/auth';
import { fetchJobLogs, fetchWebhookLogs } from '../../../../lib/api';
import { getDictionary } from '../../../../lib/i18n';

type Props = {
  searchParams?: Promise<{
    eventId?: string;
  }>;
};

function formatTime(value: string | null, pendingLabel: string) {
  if (!value) {
    return pendingLabel;
  }

  return new Date(value).toLocaleString('id-ID', {
    dateStyle: 'short',
    timeStyle: 'short',
  });
}

export default async function SettingsWebhookLogsPage({ searchParams }: Props) {
  const token = await requireAuthToken();
  const dict = await getDictionary();
  const t = dict.webhooks;
  const params = (await searchParams) || {};
  const [webhookLogs, jobLogs] = await Promise.all([fetchWebhookLogs(token), fetchJobLogs(token)]);
  const selectedLog =
    webhookLogs.find((log) => log.eventId === params.eventId) || webhookLogs[0] || null;

  return (
    <DashboardShell currentPath="/dashboard/settings/webhook-logs" title={t.title}>
      <section className="page-header">
        <div>
          <p className="page-eyebrow">{t.eyebrow}</p>
          <h1 className="page-heading">{t.title}</h1>
          <p className="page-copy">{t.description}</p>
        </div>
      </section>

      <section className="webhook-logs-layout">
        <article className="surface-card webhook-logs-card webhook-logs-table-card">
          <div className="data-table">
            <div className="data-row data-row-head webhook-grid">
              <span>{t.provider}</span>
              <span>{t.event}</span>
              <span>{t.status}</span>
              <span>{t.time}</span>
            </div>
            {webhookLogs.map((log) => (
              <Link
                key={log.id}
                href={`/dashboard/settings/webhook-logs?eventId=${encodeURIComponent(log.eventId)}`}
                className="data-row webhook-grid data-row-link"
              >
                <span>{log.provider}</span>
                <span>{log.eventType}</span>
                <span>{log.processingStatus}</span>
                <span>{formatTime((log as { createdAt?: string }).createdAt || null, t.pending)}</span>
              </Link>
            ))}
          </div>
        </article>

        <article className="surface-card code-card webhook-logs-card webhook-logs-detail-card">
          {selectedLog ? (
            <div className="detail-stack">
              <div>
                <strong>{selectedLog.eventId}</strong>
                <span>{selectedLog.eventType}</span>
              </div>
              <div>
                <strong>{selectedLog.processingStatus}</strong>
                <span>{selectedLog.processingNotes || t.noProcessingNotes}</span>
              </div>
              <div>
                <strong>{selectedLog.verified ? t.verified : t.unverified}</strong>
                <span>
                  {t.sender}: {selectedLog.senderPhone || '-'} | {t.recipient}: {selectedLog.recipientPhone || '-'}
                </span>
              </div>
              <WebhookRetryForm eventId={selectedLog.eventId} />
              <pre>{JSON.stringify(selectedLog.payloadJson, null, 2)}</pre>
            </div>
          ) : (
            <div className="webhook-empty-state">
              <span className="material-symbols-outlined">webhook</span>
              <strong>{t.empty}</strong>
              <p>{t.emptyDescription}</p>
            </div>
          )}
        </article>
      </section>

      <section className="surface-card code-card webhook-queue-card">
        <div className="card-head">
          <h2>{t.recentQueueJobs}</h2>
          <span className="soft-chip">{t.queueBadge}</span>
        </div>
        <pre>{JSON.stringify(jobLogs.slice(0, 5), null, 2)}</pre>
      </section>
    </DashboardShell>
  );
}
