import Link from 'next/link';
import { notFound } from 'next/navigation';
import { CampaignDetailActions } from '../../../../components/campaign-detail-actions';
import { DashboardShell } from '../../../../components/dashboard-shell';
import { requireAuthToken } from '../../../../lib/auth';
import { fetchCampaignDetail } from '../../../../lib/api';

function formatDateTime(value: string) {
  const date = new Date(value);
  return {
    date: date.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }),
    time: date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true }),
  };
}

function formatRecipientTime(value: string | null) {
  if (!value) {
    return '—';
  }

  const date = new Date(value);
  return `Today, ${date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true })}`;
}

function campaignStatusClassName(status: string) {
  switch (status) {
    case 'Sent':
      return 'campaign-detail-badge is-sent';
    case 'Scheduled':
      return 'campaign-detail-badge is-scheduled';
    case 'Draft':
      return 'campaign-detail-badge is-draft';
    case 'Failed':
      return 'campaign-detail-badge is-failed';
    default:
      return 'campaign-detail-badge';
  }
}

function recipientStatusClassName(status: string) {
  switch (status) {
    case 'Read':
      return 'campaign-recipient-status is-read';
    case 'Delivered':
      return 'campaign-recipient-status is-delivered';
    case 'Failed':
      return 'campaign-recipient-status is-failed';
    default:
      return 'campaign-recipient-status';
  }
}

function deviceIcon(label: string) {
  if (label === 'Android') return 'phone_android';
  if (label === 'iOS') return 'phone_iphone';
  return 'laptop';
}

export default async function CampaignDetailPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams?: Promise<{ page?: string }>;
}) {
  const token = await requireAuthToken();
  const { id } = await params;
  const query = await searchParams;
  const page = Math.max(1, Number(query?.page || '1'));

  try {
    const detail = await fetchCampaignDetail(token, id, { page, limit: 5 });
    const stamp = formatDateTime(detail.campaign.initiatedAt);

    return (
      <DashboardShell currentPath="/dashboard/campaigns">
        <div className="campaign-detail-page">
          <section className="campaign-detail-header">
            <div>
              <nav className="campaign-detail-breadcrumb">
                <Link href="/dashboard/campaigns">Campaigns</Link>
                <span className="material-symbols-outlined">chevron_right</span>
                <span>Analytics</span>
              </nav>
              <div className="campaign-detail-heading-row">
                <h1>{detail.campaign.name}</h1>
                <span className={campaignStatusClassName(detail.campaign.status)}>{detail.campaign.status}</span>
              </div>
              <p>Initiated on {stamp.date} at {stamp.time}</p>
            </div>
            <CampaignDetailActions campaign={detail.campaign} />
          </section>

          <section className="campaign-detail-kpi-grid">
            <article className="campaign-detail-kpi-card">
              <div className="campaign-detail-kpi-head">
                <span className="material-symbols-outlined">group</span>
                <span className="is-positive">
                  <span className="material-symbols-outlined">trending_up</span>
                  12%
                </span>
              </div>
              <p>Total Recipients</p>
              <strong>{detail.campaign.totalRecipients.toLocaleString('en-US')}</strong>
            </article>

            <article className="campaign-detail-kpi-card">
              <div className="campaign-detail-kpi-head">
                <span className="material-symbols-outlined is-secondary">mark_email_read</span>
                <span className="is-positive">{detail.campaign.deliveredRate.toFixed(1)}%</span>
              </div>
              <p>Delivered Rate</p>
              <strong>{detail.campaign.deliveredCount.toLocaleString('en-US')}</strong>
            </article>

            <article className="campaign-detail-kpi-card">
              <div className="campaign-detail-kpi-head">
                <span className="material-symbols-outlined is-tertiary">visibility</span>
                <span className="is-warning">
                  <span className="material-symbols-outlined">trending_down</span>
                  4%
                </span>
              </div>
              <p>Read Rate</p>
              <strong>{detail.campaign.readRate.toFixed(1)}%</strong>
            </article>

            <article className="campaign-detail-kpi-card">
              <div className="campaign-detail-kpi-head">
                <span className="material-symbols-outlined is-error">error</span>
                <span className="is-danger">{detail.campaign.failedRate.toFixed(1)}%</span>
              </div>
              <p>Failed Messages</p>
              <strong>{detail.campaign.failedCount.toLocaleString('en-US')}</strong>
            </article>
          </section>

          <section className="campaign-detail-main-grid">
            <article className="campaign-detail-card campaign-detail-timeline-card">
              <div className="campaign-detail-card-head">
                <h2>Delivery Timeline</h2>
                <select defaultValue="24h">
                  <option value="24h">Last 24 Hours</option>
                  <option value="7d">Last 7 Days</option>
                </select>
              </div>
              <div className="campaign-detail-timeline-bars">
                {detail.timeline.map((bucket, index) => (
                  <div key={`${bucket.label}-${index}`} className="campaign-detail-timeline-column">
                    <div
                      className={index === 3 ? 'campaign-detail-timeline-bar is-highlight' : 'campaign-detail-timeline-bar'}
                      style={{ height: `${bucket.height}%` }}
                      title={`${bucket.label}: ${bucket.count}`}
                    />
                  </div>
                ))}
              </div>
              <div className="campaign-detail-timeline-labels">
                {detail.timeline.filter((_, index) => index % 2 === 0).map((bucket) => (
                  <span key={bucket.label}>{bucket.label}</span>
                ))}
              </div>
            </article>

            <article className="campaign-detail-card campaign-detail-preview-card">
              <h2>Message Preview</h2>
              <div className="campaign-preview-phone">
                <img src={detail.campaign.bannerImageUrl} alt={detail.campaign.name} />
                <p className="campaign-preview-title">{detail.campaign.messageTitle}</p>
                <p className="campaign-preview-copy">{detail.campaign.messageBody}</p>
                <div className="campaign-preview-meta">
                  <span>Shop Now</span>
                  <span>{stamp.time}</span>
                </div>
                <div className="campaign-preview-buttons">
                  <button type="button">{detail.campaign.primaryButton}</button>
                  <button type="button">{detail.campaign.secondaryButton}</button>
                </div>
              </div>
              <div className="campaign-preview-foot">
                <div>
                  <span>Template Name</span>
                  <strong>{detail.campaign.templateName}</strong>
                </div>
                <div>
                  <span>Language</span>
                  <strong>{detail.campaign.language}</strong>
                </div>
              </div>
            </article>
          </section>

          <section className="campaign-detail-bottom-grid">
            <article className="campaign-detail-card campaign-detail-recipients-card">
              <div className="campaign-detail-card-head">
                <h2>Recipient List</h2>
                <div className="campaign-detail-icon-actions">
                  <button type="button"><span className="material-symbols-outlined">filter_list</span></button>
                  <button type="button"><span className="material-symbols-outlined">search</span></button>
                </div>
              </div>

              <div className="campaign-detail-table-wrap">
                <table className="campaign-detail-table">
                  <thead>
                    <tr>
                      <th>Phone Number</th>
                      <th>Status</th>
                      <th>Timestamp</th>
                      <th>Error Reason</th>
                    </tr>
                  </thead>
                  <tbody>
                    {detail.recipients.items.map((recipient) => (
                      <tr key={recipient.id}>
                        <td className="campaign-detail-mono">{recipient.phoneNumber}</td>
                        <td>
                          <div className={recipientStatusClassName(recipient.status)}>
                            <span className="material-symbols-outlined">
                              {recipient.status === 'Failed' ? 'error' : 'done_all'}
                            </span>
                            <span>{recipient.status}</span>
                          </div>
                        </td>
                        <td>{formatRecipientTime(recipient.sentAt)}</td>
                        <td>
                          {recipient.errorReason ? (
                            <span className="campaign-detail-error-pill">{recipient.errorReason}</span>
                          ) : (
                            '—'
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <div className="campaign-detail-table-footer">
                <p>
                  Showing {(detail.recipients.page - 1) * detail.recipients.pageSize + 1} to{' '}
                  {(detail.recipients.page - 1) * detail.recipients.pageSize + detail.recipients.items.length} of{' '}
                  {detail.recipients.total.toLocaleString('en-US')} recipients
                </p>
                <div className="campaign-detail-pagination">
                  <Link
                    href={`/dashboard/campaigns/${detail.campaign.id}?page=${Math.max(1, detail.recipients.page - 1)}`}
                    className={detail.recipients.page <= 1 ? 'is-disabled' : ''}
                    aria-disabled={detail.recipients.page <= 1}
                  >
                    <span className="material-symbols-outlined">chevron_left</span>
                  </Link>
                  <Link
                    href={`/dashboard/campaigns/${detail.campaign.id}?page=${Math.min(detail.recipients.totalPages, detail.recipients.page + 1)}`}
                    className={detail.recipients.page >= detail.recipients.totalPages ? 'is-disabled' : ''}
                    aria-disabled={detail.recipients.page >= detail.recipients.totalPages}
                  >
                    <span className="material-symbols-outlined">chevron_right</span>
                  </Link>
                </div>
              </div>
            </article>

            <aside className="campaign-detail-side-stack">
              <article className="campaign-detail-card">
                <h2>Device OS</h2>
                <div className="campaign-detail-device-list">
                  {detail.deviceBreakdown.map((device) => (
                    <div key={device.label} className="campaign-detail-device-row">
                      <div className="campaign-detail-device-head">
                        <span>
                          <span className="material-symbols-outlined">{deviceIcon(device.label)}</span>
                          {device.label}
                        </span>
                        <strong>{device.percentage}%</strong>
                      </div>
                      <div className="campaign-detail-device-track">
                        <span
                          className={
                            device.label === 'Android'
                              ? 'is-android'
                              : device.label === 'iOS'
                                ? 'is-ios'
                                : 'is-web'
                          }
                          style={{ width: `${device.percentage}%` }}
                        />
                      </div>
                    </div>
                  ))}
                </div>
              </article>

              <article className="campaign-detail-insight-card">
                <div className="campaign-detail-insight-icon">
                  <span className="material-symbols-outlined">rocket_launch</span>
                </div>
                <h3>Campaign Insights</h3>
                <p>
                  Engagement peaked at 11:30 AM. Personalized CTA buttons increased click-through rate by 18.5%
                  compared to previous month.
                </p>
                <button type="button">View Full Analysis</button>
              </article>
            </aside>
          </section>
        </div>
      </DashboardShell>
    );
  } catch {
    notFound();
  }
}
