import Link from 'next/link';
import { DashboardShell } from '../../../components/dashboard-shell';
import { requireAuthToken } from '../../../lib/auth';
import { fetchTemplates } from '../../../lib/api';

function templateStatusClassName(status: string) {
  if (status === 'Pending') return 'templates-status-pill is-pending';
  if (status === 'Rejected' || status === 'Archived') return 'templates-status-pill is-rejected';
  return 'templates-status-pill is-approved';
}

type Props = {
  searchParams?: Promise<{
    search?: string;
    category?: string;
    status?: string;
    language?: string;
  }>;
};

export default async function TemplatesPage({ searchParams }: Props) {
  const token = await requireAuthToken();
  const resolvedSearchParams = (await searchParams) || {};
  const search = resolvedSearchParams.search?.trim() || '';
  const category = resolvedSearchParams.category?.trim() || '';
  const status = resolvedSearchParams.status?.trim() || '';
  const language = resolvedSearchParams.language?.trim() || '';
  const templatesData = await fetchTemplates(token, {
    search: search || undefined,
    category: category || undefined,
    status: status || undefined,
    language: language || undefined,
  });

  const categoryOptions = Array.from(new Set(templatesData.items.map((template) => template.category))).sort();
  const statusOptions = Array.from(new Set(templatesData.items.map((template) => template.status))).sort();
  const languageOptions = Array.from(new Set(templatesData.items.map((template) => template.language))).sort();

  return (
    <DashboardShell
      currentPath="/dashboard/templates"
      title="Admin Dashboard"
      searchPlaceholder="Search templates..."
      searchValue={search}
      searchQueryName="search"
    >
      <section className="templates-page">
        <header className="templates-hero">
          <div>
            <h1 className="templates-heading">Message Templates</h1>
            <p className="templates-copy">
              Create and manage your WhatsApp message templates. All templates must be approved by WhatsApp before
              sending.
            </p>
          </div>
          <Link href="/dashboard/templates/builder" className="templates-create-button">
            <span className="material-symbols-outlined">add_circle</span>
            Create New Template
          </Link>
        </header>

        <form className="templates-filter-row" method="GET">
          <input type="hidden" name="search" defaultValue={search} />
          <label className="templates-filter-pill templates-filter-pill-select">
            <span>Category</span>
            <select name="category" defaultValue={category}>
              <option value="">All</option>
              {categoryOptions.map((option) => (
                <option key={option} value={option}>
                  {option}
                </option>
              ))}
            </select>
          </label>
          <label className="templates-filter-pill templates-filter-pill-select">
            <span>Status</span>
            <select name="status" defaultValue={status}>
              <option value="">All</option>
              {statusOptions.map((option) => (
                <option key={option} value={option}>
                  {option}
                </option>
              ))}
            </select>
          </label>
          <label className="templates-filter-pill templates-filter-pill-select">
            <span>Language</span>
            <select name="language" defaultValue={language}>
              <option value="">All</option>
              {languageOptions.map((option) => (
                <option key={option} value={option}>
                  {option}
                </option>
              ))}
            </select>
          </label>
          <button type="submit" className="templates-filter-apply">
            Apply
          </button>
          <div className="templates-filter-meta">Showing {templatesData.total} Templates</div>
        </form>

        <section className="templates-grid">
          {templatesData.items.filter((template) => !template.compact).map((template) => (
            <article key={template.id} className="templates-card surface-card">
              <div className="templates-card-head">
                <span className={templateStatusClassName(template.status)}>{template.status}</span>
                <Link href={`/dashboard/templates/builder?id=${template.id}`} className="templates-overflow-button">
                  <span className="material-symbols-outlined">edit</span>
                </Link>
              </div>
              <h2>{template.name}</h2>
              <p className="templates-category">{template.category}</p>
              <div className="templates-preview-box">
                <p>{template.preview}</p>
                <div className="templates-preview-fade" />
              </div>
              <footer className="templates-card-foot">
                <div className={`templates-update-meta ${template.status === 'Rejected' ? 'is-alert' : ''}`}>
                  <span className="material-symbols-outlined">
                    {template.status === 'Rejected' ? 'warning' : 'schedule'}
                  </span>
                  <span>{template.updatedLabel}</span>
                </div>
                <Link href={`/dashboard/templates/builder?id=${template.id}`} className="templates-edit-button">
                  <span className="material-symbols-outlined">edit</span>
                </Link>
              </footer>
            </article>
          ))}

          {templatesData.items
            .filter((template) => template.compact)
            .map((template) => (
              <article key={template.id} className="templates-row-card surface-card">
                <div className="templates-row-icon">
                  <span className="material-symbols-outlined">mail</span>
                </div>
                <div className="templates-row-main">
                  <h2>{template.name}</h2>
                  <div className="templates-row-meta">
                    <span>{template.category}</span>
                    <i />
                    <p>{template.preview}</p>
                  </div>
                </div>
                <div className="templates-row-date">
                  <span>Last Modified</span>
                  <strong>{template.updatedLabel}</strong>
                </div>
                <div className="templates-row-status">
                  <span className={templateStatusClassName(template.status)}>{template.status}</span>
                </div>
                <div className="templates-row-actions">
                  <Link href={`/dashboard/templates/builder?id=${template.id}`} aria-label={`Preview ${template.name}`}>
                    <span className="material-symbols-outlined">visibility</span>
                  </Link>
                  <Link
                    href={`/dashboard/templates/builder?id=${template.id}`}
                    className="is-primary"
                    aria-label={`Edit ${template.name}`}
                  >
                    <span className="material-symbols-outlined">edit</span>
                  </Link>
                </div>
              </article>
            ))}
        </section>

        <section className="templates-guidelines">
          <div className="templates-guidelines-icon">
            <span className="material-symbols-outlined">contact_support</span>
          </div>
          <div className="templates-guidelines-copy">
            <h3>Need help with Template Guidelines?</h3>
            <p>
              WhatsApp has strict policies on message content. Ensure your templates follow the Business Policy to avoid
              rejection and maintain a high quality rating.
            </p>
          </div>
          <a
            className="templates-guidelines-button"
            href="https://www.whatsapp.com/legal/business-policy/"
            target="_blank"
            rel="noreferrer"
          >
            Read Guidelines
          </a>
        </section>
      </section>
    </DashboardShell>
  );
}
