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';

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

function formatTime(value: string | null) {
  if (!value) {
    return 'Pending';
  }

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

export default async function SettingsWebhookLogsPage({ searchParams }: Props) {
  const token = await requireAuthToken();
  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">
      <section className="page-header">
        <div>
          <p className="page-eyebrow">Settings</p>
          <h1 className="page-heading">Webhook Logs</h1>
          <p className="page-copy">
            Delivery log webhook sekarang mengambil data backend nyata, termasuk status event dan job queue.
          </p>
        </div>
      </section>

      <section className="dashboard-two-column">
        <article className="surface-card">
          <div className="data-table">
            <div className="data-row data-row-head webhook-grid">
              <span>Provider</span>
              <span>Event</span>
              <span>Status</span>
              <span>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)}</span>
              </Link>
            ))}
          </div>
        </article>

        <article className="surface-card code-card">
          {selectedLog ? (
            <div className="detail-stack">
              <div>
                <strong>{selectedLog.eventId}</strong>
                <span>{selectedLog.eventType}</span>
              </div>
              <div>
                <strong>{selectedLog.processingStatus}</strong>
                <span>{selectedLog.processingNotes || 'No processing notes'}</span>
              </div>
              <div>
                <strong>{selectedLog.verified ? 'Verified' : 'Unverified'}</strong>
                <span>
                  Sender: {selectedLog.senderPhone || '-'} | Recipient: {selectedLog.recipientPhone || '-'}
                </span>
              </div>
              <WebhookRetryForm eventId={selectedLog.eventId} />
              <pre>{JSON.stringify(selectedLog.payloadJson, null, 2)}</pre>
            </div>
          ) : (
            <p>No webhook logs available.</p>
          )}
        </article>
      </section>

      <section className="surface-card code-card">
        <div className="card-head">
          <h2>Recent Queue Jobs</h2>
          <span className="soft-chip">Redis + DB audit</span>
        </div>
        <pre>{JSON.stringify(jobLogs.slice(0, 5), null, 2)}</pre>
      </section>
    </DashboardShell>
  );
}
