"use client";

import { useState } from "react";
import {
  PageHeader,
  Card,
  StatTile,
  MoneyText,
  Numeric,
  Spinner,
  ErrorState,
  SegmentedControl,
  SectionTitle,
  Button,
} from "@/components/ui";
import { useApi } from "@/hooks/useApi";
import { api } from "@/lib/api";
import { useLocale } from "@/i18n/LocaleProvider";
import { AnalyticsChart } from "@/components/AnalyticsChart";
import { downloadCsv, todayStamp } from "@/lib/csv";

type Period = "7" | "30" | "90";

export default function AnalyticsPage() {
  const { t } = useLocale();
  const [days, setDays] = useState<Period>("30");
  const { data, loading, error, reload } = useApi(() => api.analytics(Number(days)), [days]);

  const cur = data?.currency ?? "SAR";

  const exportCsv = () => {
    if (!data) return;
    // Daily time series is the exportable dataset; summary metrics ride along as leading rows.
    const rows: (string | number)[][] = [
      [t("an.grossRevenue"), data.revenue.gross, cur],
      [t("an.netTopUps"), data.topUps.net, cur],
      [t("an.rides"), data.rides.total, ""],
      [t("an.activeNow"), data.rides.active, ""],
      [],
      [t("an.date"), t("an.rideRevenueSeries"), t("an.topUpsSeries"), t("an.rides")],
      ...data.timeline.map((p) => [p.date, p.rideRevenue, p.topUps, p.rides]),
    ];
    downloadCsv(`beebbeeb-analytics-${days}d-${todayStamp()}.csv`, [], rows);
  };

  return (
    <div>
      <PageHeader
        titleKey="an.title"
        actions={
          <div className="flex flex-wrap items-center gap-2">
            <SegmentedControl<Period>
              value={days}
              onChange={setDays}
              options={[
                { value: "7", label: t("an.days7") },
                { value: "30", label: t("an.days30") },
                { value: "90", label: t("an.days90") },
              ]}
            />
            <Button variant="secondary" onClick={exportCsv} disabled={!data}>
              {t("an.export")}
            </Button>
          </div>
        }
      />
      <p className="-mt-4 mb-6 text-sm text-muted">{t("an.subtitle")}</p>

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

      {!loading && !error && data && (
        <div className="space-y-6">
          {/* Headline KPIs */}
          <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>

          {/* Timeline chart */}
          <Card>
            <SectionTitle>{t("an.timeline")}</SectionTitle>
            <div className="mt-4">
              <AnalyticsChart points={data.timeline} currency={cur} />
            </div>
          </Card>

          <div className="grid gap-6 lg:grid-cols-2">
            {/* Ride revenue breakdown */}
            <Card>
              <SectionTitle>{t("an.revenueBreakdown")}</SectionTitle>
              <dl className="mt-4 space-y-3">
                <Row label={t("an.unlockFees")}>
                  <MoneyText amount={data.revenue.unlock} currency={cur} />
                </Row>
                <Row label={t("an.perMinute")}>
                  <MoneyText amount={data.revenue.perMinute} currency={cur} />
                </Row>
                <Row label={t("an.grossRevenue")} strong>
                  <MoneyText amount={data.revenue.gross} currency={cur} />
                </Row>
                <div className="my-2 border-t border-line" />
                <Row label={t("an.avgFare")}>
                  <MoneyText amount={data.revenue.avgFare} currency={cur} />
                </Row>
                <Row label={t("an.avgDuration")}>
                  <span>
                    <Numeric>{data.rides.avgDurationMinutes.toFixed(1)}</Numeric>{" "}
                    <span className="text-xs text-muted">{t("an.minutes")}</span>
                  </span>
                </Row>
                <Row label={t("an.totalRideTime")}>
                  <span>
                    <Numeric>{Math.round(data.rides.totalMinutes / 60)}</Numeric>{" "}
                    <span className="text-xs text-muted">{t("an.hours")}</span>
                  </span>
                </Row>
                <Row label={t("an.completed")}>
                  <Numeric>{data.rides.completed}</Numeric>
                </Row>
                <Row label={t("an.dropped")}>
                  <Numeric>{data.rides.dropped}</Numeric>
                </Row>
              </dl>
            </Card>

            {/* Top-ups */}
            <Card>
              <SectionTitle>{t("an.topUps")}</SectionTitle>
              <dl className="mt-4 space-y-3">
                <Row label={t("an.topUpsGross")}>
                  <MoneyText amount={data.topUps.gross} currency={cur} />
                </Row>
                <Row label={t("an.refunds")}>
                  <span>
                    <MoneyText amount={-data.topUps.refunded} currency={cur} signed />
                    <span className="ms-2 text-xs text-muted">
                      (<Numeric>{data.topUps.refundCount}</Numeric>)
                    </span>
                  </span>
                </Row>
                <Row label={t("an.netTopUps")} strong>
                  <MoneyText amount={data.topUps.net} currency={cur} />
                </Row>
                <div className="my-2 border-t border-line" />
                <Row label={t("an.avgTopUp")}>
                  <MoneyText amount={data.topUps.avg} currency={cur} />
                </Row>
                <Row label={t("an.captureRate")}>
                  <Numeric>{(data.topUps.captureRate * 100).toFixed(1)}%</Numeric>
                </Row>
              </dl>

              {/* Package mix */}
              {data.topUps.byPackage.length > 0 && (
                <div className="mt-5">
                  <div className="mb-2 text-xs font-medium text-muted">{t("an.byPackage")}</div>
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b border-line text-xs text-muted">
                        <th className="py-1.5 text-start font-medium">{t("an.package")}</th>
                        <th className="py-1.5 text-end font-medium">{t("an.count")}</th>
                        <th className="py-1.5 text-end font-medium">{t("an.amount")}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.topUps.byPackage.map((p) => (
                        <tr key={p.code} className="border-b border-line/60">
                          <td className="py-1.5">{p.code === "CUSTOM" ? t("an.custom") : p.code}</td>
                          <td className="py-1.5 text-end">
                            <Numeric>{p.count}</Numeric>
                          </td>
                          <td className="py-1.5 text-end">
                            <Numeric>{p.total.toFixed(2)}</Numeric> {cur}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </Card>
          </div>
        </div>
      )}
    </div>
  );
}

function Row({
  label,
  children,
  strong = false,
}: {
  label: string;
  children: React.ReactNode;
  strong?: boolean;
}) {
  return (
    <div className="flex items-center justify-between gap-4">
      <dt className={`text-sm ${strong ? "font-semibold text-foreground" : "text-muted"}`}>
        {label}
      </dt>
      <dd className={strong ? "font-semibold" : ""}>{children}</dd>
    </div>
  );
}
