import { notFound } from 'next/navigation';
import Link from 'next/link';
import type { Route } from 'next';
import { ArrowRight, ChevronLeft, Wrench } from 'lucide-react';

import { PageHeader } from '@/components/shared/page-header';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DashboardReportBuilder } from '@/components/reports/builders/dashboard-report-builder';
import { SimpleReportBuilder } from '@/components/reports/builders/simple-report-builder';

/**
 * Two generations of report kinds live here:
 *
 *  - LEGACY_KINDS: the original 2026-Q1 builders (dashboard, clients,
 *    berths, interests). Functional today via the existing
 *    SimpleReportBuilder / DashboardReportBuilder.
 *  - NEW_KINDS: the four canonical categories from the 2026-05-27 launch
 *    initiative (sales, financial, marketing, operational), plus the
 *    custom ad-hoc composer. Each currently renders a placeholder so
 *    the new landing page routes here without 404-ing; the actual
 *    builders ship per the launch-readiness doc.
 */
const LEGACY_KINDS = ['dashboard', 'clients', 'berths', 'interests'] as const;
const NEW_KINDS = ['sales', 'financial', 'marketing', 'operational', 'custom'] as const;

type LegacyKind = (typeof LEGACY_KINDS)[number];
type NewKind = (typeof NEW_KINDS)[number];

/**
 * NEW_KINDS that have a card on the /reports landing page each own a
 * dedicated route (reports/sales, reports/operational, reports/financial,
 * reports/custom) which shadows this dynamic segment. The only NEW_KIND that
 * still resolves here is `marketing`, whose builder is blocked on the website
 * cutover (launch-readiness Initiative 1b) and currently renders only an "in
 * development" placeholder. Gate it to a 404 for beta so it can't be reached
 * via a hand-typed URL or a stale saved template. Remove the entry when the
 * Marketing report ships.
 */
const UNAVAILABLE_NEW_KINDS: readonly NewKind[] = ['marketing'];

interface PageProps {
  params: Promise<{ portSlug: string; kind: string }>;
  searchParams: Promise<{ from?: string; to?: string }>;
}

const LEGACY_LABELS: Record<LegacyKind, { title: string; description: string }> = {
  dashboard: {
    title: 'Dashboard report',
    description: 'Multi-section PDF of the port dashboard - pick which sections to include.',
  },
  clients: { title: 'Clients report', description: 'Activity snapshot for active clients.' },
  berths: { title: 'Berths report', description: 'Occupancy + status mix per berth.' },
  interests: { title: 'Interests report', description: 'Pipeline value + stage distribution.' },
};

const NEW_LABELS: Record<NewKind, { title: string; description: string }> = {
  sales: {
    title: 'Sales performance',
    description: 'Rep leaderboards, win rates, time-to-close, stalled deals, conversion funnel.',
  },
  financial: {
    title: 'Financial',
    description: 'Revenue by month, deposits collected, AR aging, EOI to revenue conversion.',
  },
  marketing: {
    title: 'Marketing & funnel',
    description: 'Lead source ROI, inquiry-to-EOI conversion, attribution by campaign.',
  },
  operational: {
    title: 'Operational',
    description: 'Berth utilisation, occupancy heatmap, tenancy churn, signing turnaround.',
  },
  custom: {
    title: 'Custom report',
    description:
      'Compose your own. Pick an entity, choose columns and filters, group by any dimension.',
  },
};

export default async function ReportBuilderPage({ params, searchParams }: PageProps) {
  const { portSlug, kind } = await params;
  const { from, to } = await searchParams;

  const isLegacy = (LEGACY_KINDS as readonly string[]).includes(kind);
  const isNew = (NEW_KINDS as readonly string[]).includes(kind);
  if (!isLegacy && !isNew) notFound();

  // Unbuilt report kinds (currently just Marketing) 404 rather than show the
  // "in development" placeholder — keeps the beta reports surface looking
  // complete. See UNAVAILABLE_NEW_KINDS above.
  if ((UNAVAILABLE_NEW_KINDS as readonly string[]).includes(kind)) notFound();

  if (isLegacy) {
    const typedKind = kind as LegacyKind;
    const labels = LEGACY_LABELS[typedKind];
    return (
      <div className="space-y-4">
        <PageHeader eyebrow="Reports" title={labels.title} description={labels.description} />
        {typedKind === 'dashboard' ? (
          <DashboardReportBuilder portSlug={portSlug} initialFrom={from} initialTo={to} />
        ) : (
          <SimpleReportBuilder portSlug={portSlug} kind={typedKind} />
        )}
      </div>
    );
  }

  // New-kind placeholder. Uses the standard PageHeader + Card pattern so
  // it reads as part of the same app while the actual builders ship.
  const typedKind = kind as NewKind;
  const labels = NEW_LABELS[typedKind];
  return (
    <div className="space-y-4">
      <PageHeader eyebrow="Reports" title={labels.title} description={labels.description} />

      <Card>
        <CardHeader className="flex flex-row items-start gap-3 space-y-0">
          <Wrench className="h-5 w-5 mt-0.5 text-muted-foreground" aria-hidden />
          <div className="flex-1">
            <CardTitle className="text-base">Builder in development</CardTitle>
            <CardDescription className="mt-1">
              The {labels.title.toLowerCase()} builder is shipping as part of the active launch
              initiative. In the meantime the legacy builders below cover most of the same data.
            </CardDescription>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex flex-wrap gap-2">
            <Button asChild variant="outline" size="sm">
              <Link href={`/${portSlug}/reports` as Route}>
                <ChevronLeft className="mr-1.5 h-4 w-4" aria-hidden />
                Back to reports
              </Link>
            </Button>
            <Button asChild size="sm">
              <Link href={`/${portSlug}/reports/dashboard` as Route}>
                Open dashboard report
                <ArrowRight className="ml-1.5 h-4 w-4" aria-hidden />
              </Link>
            </Button>
          </div>
        </CardContent>
      </Card>

      <section className="space-y-3">
        <div>
          <h2 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
            Legacy builders
          </h2>
          <p className="text-xs text-muted-foreground/80">
            Available now while the new category builders are filled in.
          </p>
        </div>
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {(LEGACY_KINDS as readonly LegacyKind[]).map((k) => (
            <Link key={k} href={`/${portSlug}/reports/${k}` as Route} className="block group">
              <Card className="h-full transition-colors group-hover:border-primary/50 group-hover:bg-muted/30">
                <CardHeader className="pb-2">
                  <CardTitle className="text-base">{LEGACY_LABELS[k].title}</CardTitle>
                </CardHeader>
                <CardContent>
                  <CardDescription>{LEGACY_LABELS[k].description}</CardDescription>
                </CardContent>
              </Card>
            </Link>
          ))}
        </div>
      </section>
    </div>
  );
}
