"use client";

import Link from "next/link";
import {
  PageHeader,
  StatTile,
  Card,
  SectionTitle,
  Button,
  Spinner,
  ErrorState,
} from "@/components/ui";
import { useApi } from "@/hooks/useApi";
import { api, getSession } from "@/lib/api";
import { useLocale } from "@/i18n/LocaleProvider";
import { downloadCsv, todayStamp } from "@/lib/csv";

const STATUS_STYLE: Record<string, string> = {
  AVAILABLE: "bg-emerald-500",
  IN_USE: "bg-brand-deep",
  LOW_BATTERY: "bg-amber-500",
  MAINTENANCE: "bg-slate-400",
  OFFLINE: "bg-red-400",
};

/** Roles allowed to see revenue on the overview (matches the analytics endpoint's RBAC). */
const FINANCE_ROLES = ["SUPER_ADMIN", "FINANCE"];

export default function DashboardPage() {
  const { t } = useLocale();
  const { data, loading, error, reload } = useApi(() => api.fleetSummary());

  const by = data?.byStatus ?? {};
  const get = (k: string) => by[k] ?? 0;

  const exportFleet = () => {
    if (!data) return;
    const rows = Object.entries(by).map(([status, count]) => [status, count]);
    rows.push([t("common.total"), data.total]);
    downloadCsv(`beebbeeb-fleet-${todayStamp()}.csv`, [t("dash.status"), t("dash.count")], rows);
  };

  const role = getSession()?.role ?? "";
  const showFinancial = FINANCE_ROLES.includes(role);

  return (
    <div>
      <PageHeader
        titleKey="dash.title"
        actions={
          data ? (
            <Button variant="secondary" onClick={exportFleet}>
              {t("dash.exportFleet")}
            </Button>
          ) : undefined
        }
      />

      {loading && <Spinner />}
      {!loading && !!error && <ErrorState onRetry={reload} />}

      {!loading && !error && data && (
        <div className="space-y-6">
          {/* Financial + operational overview (finance roles only) */}
          {showFinancial && <FinancialOverview />}

          {/* Fleet status */}
          <div className="grid grid-cols-2 gap-4 md:grid-cols-3">
            <StatTile label={t("dash.fleetTotal")} value={data.total} accent />
            <StatTile label={t("dash.available")} value={get("AVAILABLE")} />
            <StatTile label={t("dash.inUse")} value={get("IN_USE")} />
            <StatTile label={t("dash.lowBattery")} value={get("LOW_BATTERY")} />
            <StatTile label={t("dash.maintenance")} value={get("MAINTENANCE")} />
            <StatTile label={t("dash.offline")} value={get("OFFLINE")} />
          </div>

          <Card>
            <div className="mb-3 text-sm font-semibold">{t("dash.byStatus")}</div>
            <div className="flex h-3 w-full overflow-hidden rounded-full bg-background">
              {Object.entries(by).map(([status, count]) =>
                data.total > 0 ? (
                  <div
                    key={status}
                    className={STATUS_STYLE[status] ?? "bg-slate-300"}
                    style={{ width: `${(count / data.total) * 100}%` }}
                    title={`${status}: ${count}`}
                  />
                ) : null,
              )}
            </div>
            <div className="mt-4 flex flex-wrap gap-x-6 gap-y-2 text-xs text-muted">
              {Object.entries(by).map(([status, count]) => (
                <span key={status} className="inline-flex items-center gap-2">
                  <span
                    className={`h-2.5 w-2.5 rounded-full ${
                      STATUS_STYLE[status] ?? "bg-slate-300"
                    }`}
                  />
                  {status} · {count}
                </span>
              ))}
            </div>
          </Card>
        </div>
      )}
    </div>
  );
}

/**
 * A compact revenue/top-up/ride snapshot for the overview (last 30 days), with a link into the full
 * Analytics page. Loads independently so a slow or forbidden analytics call never blocks the fleet
 * tiles above  and it only mounts for finance roles, so no 403 noise for OPS/SUPPORT.
 */
function FinancialOverview() {
  const { t } = useLocale();
  const { data, loading, error } = useApi(() => api.analytics(30));

  if (loading || error || !data) {
    // Silent skip: the overview is a bonus on top of the fleet view, not load-bearing.
    return loading ? <div className="card h-28 animate-pulse" /> : null;
  }

  const cur = data.currency;
  return (
    <Card>
      <div className="mb-4 flex items-center justify-between gap-4">
        <SectionTitle>{t("dash.financialTitle")}</SectionTitle>
        <Link href="/analytics" className="text-sm text-brand underline">
          {t("dash.viewAnalytics")}
        </Link>
      </div>
      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <StatTile
          label={t("an.grossRevenue")}
          value={`${data.revenue.gross.toFixed(2)} ${cur}`}
          tone="brand"
        />
        <StatTile
          label={t("an.netTopUps")}
          value={`${data.topUps.net.toFixed(2)} ${cur}`}
          tone="success"
        />
        <StatTile label={t("an.rides")} value={data.rides.total} />
        <StatTile label={t("an.activeNow")} value={data.rides.active} tone="info" />
      </div>
    </Card>
  );
}
