import type { CategoryModeDto, CategoryOperatingMode } from '@navi/types';
import { AccessDenied } from '../../../components/AccessDenied';
import { EmptyState, Notice, PageHeader, StatusBadge } from '../../../components/DashboardPrimitives';
import { dashboardApi } from '../../../lib/api';
import { requireDashboardRoute } from '../../../lib/permissions';
import { updateCategoryModeAction } from './actions';

const MODES: CategoryOperatingMode[] = [
  'DISABLED',
  'MARKETING_ONLY',
  'INQUIRY_ONLY',
  'DEMO_ONLY',
  'SANDBOX_READY',
  'LIVE_READY',
];

const MODE_HELP: Record<CategoryOperatingMode, string> = {
  DISABLED: 'Hidden or unavailable. No customer CTA should imply service availability.',
  MARKETING_ONLY: 'Safe for landing pages and partner acquisition. No booking, payment, or order action.',
  INQUIRY_ONLY: 'Users may express interest or contact Navi. No confirmed booking/payment.',
  DEMO_ONLY: 'Demo data only and never production-confirmed.',
  SANDBOX_READY: 'Provider sandbox can be tested. Not live transaction ready.',
  LIVE_READY: 'Approved for production operations when matching provider integrations are also live.',
};

export default async function CategoryModes({ searchParams }: { searchParams?: { status?: string; error?: string } }) {
  const gate = await requireDashboardRoute('/category-modes');
  if (!gate.allowed) return <AccessDenied required={gate.required} />;

  const categories = (await dashboardApi<CategoryModeDto[]>('/provider-control/category-modes')) ?? [];

  return (
    <div className="stack">
      <PageHeader title="Category modes" eyebrow="Control Tower">
        <span className="muted">Controls what Navi can safely market, demo, sandbox, or sell live.</span>
      </PageHeader>

      <section className="metric-grid">
        {MODES.map((mode) => (
          <div key={mode} className="metric-card">
            <StatusBadge value={mode} />
            <p className="metric-hint">{MODE_HELP[mode]}</p>
          </div>
        ))}
      </section>

      {searchParams?.status ? (
        <Notice tone="success" title="Category mode updated" body="The API persisted the mode change and wrote an audit log." />
      ) : null}
      {searchParams?.error ? (
        <Notice tone="error" title="Mode update failed" body="The request was blocked or failed. Check permissions and API logs." />
      ) : null}

      <div className="card">
        {categories.length ? (
          <div className="table-wrap">
            <table className="table">
              <thead>
                <tr>
                  <th>Category</th>
                  <th>Kind</th>
                  <th>Current mode</th>
                  <th>Change mode</th>
                  <th>Audit note</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                {categories.map((category) => (
                  <tr key={category.id}>
                    <td>
                      <strong>{category.name}</strong>
                      <div className="muted mono">{category.slug}</div>
                      <div className="muted" style={{ marginTop: 6 }}>{MODE_HELP[category.operatingMode]}</div>
                    </td>
                    <td><StatusBadge value={category.kind} /></td>
                    <td><StatusBadge value={category.operatingMode} /></td>
                    <td>
                      <form id={`category-mode-${category.id}`} action={updateCategoryModeAction} className="button-row">
                        <input type="hidden" name="categoryId" value={category.id} />
                        <select className="input" name="operatingMode" defaultValue={category.operatingMode} aria-label={`Mode for ${category.name}`}>
                          {MODES.map((mode) => (
                            <option key={mode} value={mode}>{mode.replace(/_/g, ' ')}</option>
                          ))}
                        </select>
                      </form>
                    </td>
                    <td>
                      <input
                        className="input"
                        form={`category-mode-${category.id}`}
                        name="note"
                        placeholder="Reason for audit trail"
                        aria-label={`Audit note for ${category.name}`}
                      />
                    </td>
                    <td>
                      <button className="btn-primary" form={`category-mode-${category.id}`} type="submit">Save</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <EmptyState title="No categories found" body="Seed or create categories first. Category operating modes cannot be managed without real category records." />
        )}
      </div>
    </div>
  );
}
