import { AlertCircle, ArrowDownRight, ArrowUpRight, Minus, Wallet } from 'lucide-react';

import { Head, Link, router, usePage } from '@inertiajs/react';

import EditorialPageHeader from '@/Components/layout/EditorialPageHeader';
import { Card, CardContent, CardHeader, CardTitle } from '@/Components/ui/card';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { formatCurrency, formatNumber, formatPercentRaw } from '@/lib/format';
import { cn } from '@/lib/utils';
import type { PageProps } from '@/types';

interface PortfolioSummary {
  mtd_spend: number;
  projected_eom: number;
  mom_change_pct: number;
  active_site_count: number;
  effective_cap: number;
  cap_unlimited: boolean;
  cap_utilization_pct: number;
  approaching_cap: boolean;
  lifetime_batches: number;
  /** R6PROD-012: true when pending/scheduled spend inflated the projection above linear burn. */
  includes_scheduled: boolean;
  /** R6PROD-012: true when projected_eom (with committed spend) would exceed the cap. */
  scheduled_breach_warning: boolean;
  /** ROI-004: sum of significant recovered clicks across all active sites. Null until ROI is tracked. */
  total_clicks_recovered: number | null;
  /** ROI-004: MTD spend divided by total recovered clicks. Null until ROI is tracked. */
  cost_per_click_gained: number | null;
}

interface SiteRow {
  id: string;
  name: string;
  mtd_spend: number;
  projected_eom: number;
  cost_per_click_gained: number | null;
  effective_cap: number;
  cap_unlimited: boolean;
  cap_utilization_pct: number;
}

interface TrendPoint {
  year_month: string;
  total_spend: number;
}

interface Props {
  portfolio: PortfolioSummary;
  sites: SiteRow[];
  trend: TrendPoint[];
}

/** Color class for a cap-utilization percentage (green/amber/red bands). */
function utilizationTone(pct: number, unlimited: boolean): string {
  if (unlimited) return 'text-muted-foreground';
  if (pct >= 80) return 'text-destructive-strong';
  if (pct >= 50) return 'text-warning-strong';
  return 'text-success-strong';
}

function MomBadge({ pct }: { pct: number }) {
  if (pct === 0) {
    return (
      <span className="inline-flex items-center gap-1 text-muted-foreground">
        <Minus className="size-3.5" aria-hidden /> no change
      </span>
    );
  }
  const up = pct > 0;
  return (
    <span
      className={cn(
        'inline-flex items-center gap-1',
        up ? 'text-destructive-strong' : 'text-success-strong',
      )}
    >
      {up ? (
        <ArrowUpRight className="size-3.5" aria-hidden />
      ) : (
        <ArrowDownRight className="size-3.5" aria-hidden />
      )}
      {formatPercentRaw(Math.abs(pct))} vs last month
    </span>
  );
}

function CapUtilizationBar({ pct, unlimited }: { pct: number; unlimited: boolean }) {
  if (unlimited) {
    return <p className="text-sm text-muted-foreground">No cap (unlimited plan)</p>;
  }
  const clamped = Math.min(100, pct);
  const barTone =
    pct >= 80 ? 'bg-destructive' : pct >= 50 ? 'bg-warning' : 'bg-success';
  return (
    <div className="space-y-1">
      <div className="h-2 w-full overflow-hidden rounded-full bg-muted">
        <div
          className={cn('h-full rounded-full transition-all', barTone)}
          style={{ width: `${clamped}%` }}
          role="progressbar"
          aria-valuenow={Math.round(pct)}
          aria-valuemin={0}
          aria-valuemax={100}
          aria-label="Monthly spend cap utilization"
        />
      </div>
      <p className={cn('text-xs', utilizationTone(pct, unlimited))}>
        {formatPercentRaw(pct)} of cap used
      </p>
    </div>
  );
}

// D4-C-003: CTA points to the action that creates spend (generating a draft), not the dashboard.
// UXB-R16-01: use a solo-reachable destination (dashboard or sites.create) — never the
// feature-gated portfolio route which 404s for the single-site solo persona.
function EmptyState({ hasSites }: { hasSites: boolean }) {
  const ctaHref = hasSites ? route('dashboard') : route('sites.create');
  const ctaLabel = hasSites ? 'Go to your dashboard →' : 'Add your first site →';

  return (
    <Card variant="flat">
      <CardContent className="flex flex-col items-center gap-3 py-12 text-center">
        <Wallet className="size-8 text-muted-foreground" aria-hidden />
        <h2 className="text-lg font-semibold text-foreground">No spend yet</h2>
        <p className="max-w-md text-sm text-muted-foreground">
          Your spend will show up once you run your first AI batch. Pick a site, open its
          recommendations, and generate a draft to start tracking your AI budget.
        </p>
        <Link
          href={ctaHref}
          className="rounded-sm text-sm font-medium text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
        >
          {ctaLabel}
        </Link>
      </CardContent>
    </Card>
  );
}

// D4-C-008: distinct error state for when spend data fails to load.
function ErrorState() {
  return (
    <Card variant="flat">
      <CardContent className="flex flex-col items-center gap-3 py-12 text-center">
        <AlertCircle className="size-8 text-destructive" aria-hidden />
        <h2 className="text-lg font-semibold text-foreground">Couldn&rsquo;t load spend data</h2>
        <p className="max-w-md text-sm text-muted-foreground">
          Something went wrong fetching your spend summary. Your data is safe — try refreshing
          the page.
        </p>
        <button
          type="button"
          onClick={() => window.location.reload()}
          className="rounded-sm text-sm font-medium text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
        >
          Refresh page &rarr;
        </button>
      </CardContent>
    </Card>
  );
}


export default function SpendIndex({ portfolio, sites, trend }: Props) {
  const { auth, flash } = usePage<PageProps>().props;
  void auth;

  const isEmpty = portfolio.mtd_spend === 0 && portfolio.lifetime_batches === 0;
  // D4-C-008: treat a flash.error on this page as a spend-data load failure.
  const hasError = !!flash.error;

  const maxTrend = Math.max(1, ...trend.map((t) => t.total_spend));

  return (
    <DashboardLayout>
      <Head title="Spend" />

      <div className="container py-6">
        {/* F5UXA-017: solo users (single site) see a focused view — no portfolio framing.
            'SITES' eyebrow and per-site table only render when the user has >1 site. */}
        <EditorialPageHeader
          eyebrow={portfolio.active_site_count > 1 ? `SPEND · ${portfolio.active_site_count} SITES` : 'SPEND'}
          title="Spend"
          subtitle="Where your AI budget is going this month."
          readouts={[
            { label: 'Month to date', value: formatCurrency(portfolio.mtd_spend) },
            {
              label: 'Projected',
              value: portfolio.projected_eom > 0 ? formatCurrency(portfolio.projected_eom) : '—',
            },
            {
              label: 'Cap',
              value: portfolio.cap_unlimited ? 'Unlimited' : formatCurrency(portfolio.effective_cap),
            },
            ...(portfolio.total_clicks_recovered !== null
              ? [
                  {
                    label: 'Clicks measured',
                    value: formatNumber(portfolio.total_clicks_recovered),
                    wrapperClassName: 'hidden md:flex',
                  },
                  {
                    label: 'Cost / click',
                    value:
                      portfolio.cost_per_click_gained !== null
                        ? formatCurrency(portfolio.cost_per_click_gained)
                        : '—',
                    wrapperClassName: 'hidden md:flex',
                  },
                ]
              : []),
          ]}
        />

        {hasError ? (
          <div className="mt-6">
            <ErrorState />
          </div>
        ) : isEmpty ? (
          <div className="mt-6">
            <EmptyState hasSites={portfolio.active_site_count > 0} />
          </div>
        ) : (
          <div className="mt-6 space-y-6">
            {portfolio.approaching_cap && (
              <Card variant="flat" className="border-warning-border bg-warning-soft">
                <CardContent className="py-4 text-sm text-warning-strong">
                  You&rsquo;ve used {formatPercentRaw(portfolio.cap_utilization_pct)} of your
                  monthly AI spend cap. Raise it in{' '}
                  <Link
                    href={route('settings.budget')}
                    className="font-medium underline underline-offset-4"
                  >
                    Budget settings
                  </Link>{' '}
                  if you need more room.
                </CardContent>
              </Card>
            )}

            {portfolio.scheduled_breach_warning && (
              <Card variant="flat" className="border-destructive/40 bg-destructive/5">
                <CardContent className="py-4 text-sm text-destructive-strong">
                  A queued batch or scheduled autopilot run is projected to exceed your monthly
                  cap.{' '}
                  <Link
                    href={route('settings.budget')}
                    className="font-medium underline underline-offset-4"
                  >
                    Raise your cap
                  </Link>{' '}
                  or cancel pending batches before they process.
                </CardContent>
              </Card>
            )}

            {/* Portfolio header tile */}
            <div
              className={cn(
                'grid gap-4',
                portfolio.total_clicks_recovered !== null
                  ? 'sm:grid-cols-2 lg:grid-cols-4'
                  : 'sm:grid-cols-3',
              )}
            >
              <Card variant="flat">
                <CardHeader className="pb-2">
                  <CardTitle className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
                    Month to date
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-1">
                  <p className="font-data text-2xl text-foreground">
                    {formatCurrency(portfolio.mtd_spend)}
                  </p>
                  <p className="text-xs">
                    <MomBadge pct={portfolio.mom_change_pct} />
                  </p>
                </CardContent>
              </Card>

              <Card variant="flat">
                <CardHeader className="pb-2">
                  <CardTitle className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
                    Projected end of month
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-1">
                  <p className="font-data text-2xl text-foreground">
                    {portfolio.projected_eom > 0 ? formatCurrency(portfolio.projected_eom) : '—'}
                  </p>
                  <p className="text-xs text-muted-foreground">
                    {portfolio.includes_scheduled
                      ? 'Includes queued & scheduled spend.'
                      : 'Assumes current burn continues.'}
                  </p>
                </CardContent>
              </Card>

              <Card variant="flat">
                <CardHeader className="pb-2">
                  <CardTitle className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
                    Cap utilization
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <CapUtilizationBar
                    pct={portfolio.cap_utilization_pct}
                    unlimited={portfolio.cap_unlimited}
                  />
                </CardContent>
              </Card>

              {/* ROI-004: measured-clicks card — only rendered when ROI has been tracked */}
              {portfolio.total_clicks_recovered !== null && (
                <Card variant="flat">
                  <CardHeader className="pb-2">
                    <CardTitle className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
                      Clicks measured
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-1">
                    <p className="font-data text-2xl text-foreground">
                      {formatNumber(portfolio.total_clicks_recovered)}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      {portfolio.cost_per_click_gained !== null
                        ? `${formatCurrency(portfolio.cost_per_click_gained)} per measured click`
                        : '—'}
                    </p>
                  </CardContent>
                </Card>
              )}
            </div>

            {/* 3-month trend */}
            <Card variant="flat">
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-semibold text-foreground">
                  3-month spend trend
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-end gap-4" style={{ height: 96 }}>
                  {trend.map((point) => (
                    <div key={point.year_month} className="flex flex-1 flex-col items-center gap-1">
                      <div className="flex w-full flex-1 items-end justify-center">
                        <div
                          className="w-8 rounded-t bg-primary/70"
                          style={{ height: `${Math.max(2, (point.total_spend / maxTrend) * 100)}%` }}
                          aria-hidden
                        />
                      </div>
                      <span className="font-data text-xs text-foreground">
                        {formatCurrency(point.total_spend)}
                      </span>
                      <span className="text-[10px] uppercase tracking-wide text-muted-foreground">
                        {point.year_month}
                      </span>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            {/* Per-site table — only rendered for multi-site users (F5UXA-017).
                Single-site solo users (the v1 persona) see the summary cards above
                without a one-row "By site" table that adds no information. */}
            {portfolio.active_site_count > 1 && (
              <Card variant="flat">
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm font-semibold text-foreground">By site</CardTitle>
                </CardHeader>
                <CardContent className="px-0">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b border-border text-left text-xs uppercase tracking-wide text-muted-foreground">
                        <th className="px-6 py-2 font-medium">Site</th>
                        <th className="px-6 py-2 text-right font-medium">Month to date</th>
                        <th className="px-6 py-2 text-right font-medium">Projected</th>
                        <th className="px-6 py-2 text-right font-medium">Cap</th>
                        <th className="px-6 py-2 text-right font-medium">Utilization</th>
                        <th className="px-6 py-2 text-right font-medium">Cost / click</th>
                      </tr>
                    </thead>
                    <tbody>
                      {sites.map((site) => (
                        <tr key={site.id} className="border-b border-border/60 last:border-0">
                          <td className="px-6 py-3 font-medium">
                            <button
                              type="button"
                              onClick={() => router.visit(route('pipeline.index', site.id))}
                              className="text-foreground underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-sm"
                            >
                              {site.name}
                            </button>
                          </td>
                          <td className="px-6 py-3 text-right font-data text-foreground">
                            {formatCurrency(site.mtd_spend)}
                          </td>
                          <td className="px-6 py-3 text-right font-data text-muted-foreground">
                            {site.projected_eom > 0 ? formatCurrency(site.projected_eom) : '—'}
                          </td>
                          <td className="px-6 py-3 text-right font-data text-muted-foreground">
                            {site.cap_unlimited ? 'Unlimited' : formatCurrency(site.effective_cap)}
                          </td>
                          <td
                            className={cn(
                              'px-6 py-3 text-right font-data',
                              utilizationTone(site.cap_utilization_pct, site.cap_unlimited),
                            )}
                          >
                            {site.cap_unlimited ? '—' : formatPercentRaw(site.cap_utilization_pct)}
                          </td>
                          <td className="px-6 py-3 text-right font-data text-muted-foreground">
                            {site.cost_per_click_gained !== null
                              ? formatCurrency(site.cost_per_click_gained)
                              : '—'}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </CardContent>
              </Card>
            )}

            <div>
              <Link
                href={route('settings.budget')}
                className="inline-flex items-center gap-2 rounded-sm text-sm font-medium text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
              >
                <Wallet className="size-4" aria-hidden /> Manage your monthly budget cap
              </Link>
            </div>
          </div>
        )}
      </div>
    </DashboardLayout>
  );
}
