"use client";

import { useRouter } from "next/navigation";
import { PageHeader, Panel, Metric } from "@/components/shared/page";
import { Button } from "@/components/ui/button";
import { currency } from "@/lib/format";
import { downloadCsv } from "@/lib/export";
import { SessionAnalyticsChart } from "./session-analytics-chart";
import type {
  SessionActiveUsersReport,
  SessionCostReport,
  SessionMeanChargingReport,
  SessionNewUsersReport,
  SessionRevenueReport,
  SessionReturningUsersReport,
} from "./session-analytics-contract";

type SharedProps = {
  startDate: string;
  endDate: string;
  today: string;
};

type Props =
  | (SharedProps & {
      report: "revenue";
      revenueData: SessionRevenueReport | null;
      revenueError: string | null;
      costData: SessionCostReport | null;
      costError: string | null;
    })
  | (SharedProps & {
      report: "behavior";
      data: SessionActiveUsersReport | null;
      error: string | null;
      returningUsersData: SessionReturningUsersReport | null;
      returningUsersError: string | null;
      meanChargingData: SessionMeanChargingReport | null;
      meanChargingError: string | null;
      newUsersData: SessionNewUsersReport | null;
      newUsersError: string | null;
      newUsersStartDate: string;
      newUsersEndDate: string;
    });

function RevenueReport({
  data,
  startDate,
  endDate,
  today,
}: {
  data: SessionRevenueReport;
} & SharedProps) {
  const rows = data.summary;

  return (
    <section className="space-y-4">
      <h2 className="text-lg font-semibold">Session Revenue</h2>
      <div className="grid gap-4 sm:grid-cols-3">
        <Metric label="Total Revenue" value={currency(data.totalRevenue)} />
        <Metric label="Energy Bill" value={currency(data.totalEnergyBill)} />
        <Metric label="Profit" value={currency(data.totalProfit)} />
      </div>
      <div className="grid gap-5 xl:grid-cols-2">
        <SessionAnalyticsChart
          metric="revenue-profit"
          title="Revenue and Profit"
          initialData={data}
          startDate={startDate}
          endDate={endDate}
          today={today}
        />
        <SessionAnalyticsChart
          metric="energy-bill"
          title="Energy Bill"
          initialData={data}
          startDate={startDate}
          endDate={endDate}
          today={today}
        />
      </div>
      <div className="flex justify-end">
        <Button
          type="button"
          variant="outline"
          onClick={() =>
            downloadCsv(
              "Revenue and Cost Analysis",
              rows.map((row) => ({
                Date: row.date,
                Revenue: row.revenue,
                "Energy Bill": row.energyBill,
                Profit: row.profit,
              })),
            )
          }
        >
          Export CSV
        </Button>
      </div>
    </section>
  );
}

function CostReport({
  data,
  startDate,
  endDate,
  today,
}: {
  data: SessionCostReport;
} & SharedProps) {
  const rows = data.summary;

  return (
    <section className="space-y-4">
      <div>
        <h2 className="text-lg font-semibold">Session Cost</h2>
        <p className="mt-1 text-sm text-muted-foreground">
          Totals and cost components are shown as returned by the API.
        </p>
      </div>
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        <Metric label="Total Cost" value={currency(data.totalCost)} />
        <Metric label="Energy Cost" value={currency(data.totalEnergyCost)} />
        <Metric label="Time Cost" value={currency(data.totalTimeCost)} />
        <Metric label="Idle Cost" value={currency(data.totalIdleCost)} />
      </div>
      <SessionAnalyticsChart
        metric="cost"
        title="Cost by Period"
        initialData={data}
        startDate={startDate}
        endDate={endDate}
        today={today}
      />
      <div className="flex justify-end">
        <Button
          type="button"
          variant="outline"
          onClick={() =>
            downloadCsv(
              "Session Cost",
              rows.map((row) => ({
                Date: row.date,
                "Energy Cost": row.energyCost,
                "Time Cost": row.timeCost,
                "Idle Cost": row.idleCost,
              })),
            )
          }
        >
          Export Cost CSV
        </Button>
      </div>
    </section>
  );
}

function ActiveUsersReport({
  data,
  error,
  returningUsersData,
  returningUsersError,
  meanChargingData,
  meanChargingError,
  newUsersData,
  newUsersError,
  newUsersStartDate,
  newUsersEndDate,
  startDate,
  endDate,
  today,
}: {
  data: SessionActiveUsersReport | null;
  error: string | null;
  returningUsersData: SessionReturningUsersReport | null;
  returningUsersError: string | null;
  meanChargingData: SessionMeanChargingReport | null;
  meanChargingError: string | null;
  newUsersData: SessionNewUsersReport | null;
  newUsersError: string | null;
  newUsersStartDate: string;
  newUsersEndDate: string;
} & SharedProps) {
  const countsByDate = new Map<string, number>(
    (data?.summary ?? []).map((row) => [row.date, row.activeUsers] as const),
  );
  const dailySummary: Array<{ date: string; activeUsers: number }> = [];
  for (
    let timestamp = Date.parse(startDate + "T00:00:00.000Z");
    timestamp <= Date.parse(endDate + "T00:00:00.000Z");
    timestamp += 86_400_000
  ) {
    const date = new Date(timestamp).toISOString().slice(0, 10);
    dailySummary.push({ date, activeUsers: countsByDate.get(date) ?? 0 });
  }
  const dailyCounts = dailySummary.map((row) => row.activeUsers);
  const average = dailyCounts.length
    ? dailyCounts.reduce((sum, value) => sum + value, 0) / dailyCounts.length
    : 0;
  const peak = dailyCounts.reduce((highest, value) => Math.max(highest, value), 0);

  return (
    <div className="space-y-6">
      {error ? (
        <ReportUnavailable title="Active Users unavailable" error={error} />
      ) : data ? (
        <section className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-3">
            <Metric
              label="Unique Active Users"
              value={data.totalActiveUsers.toLocaleString()}
            />
            <Metric label="Average Daily Active Users" value={average.toFixed(1)} />
            <Metric label="Peak Daily Active Users" value={peak.toLocaleString()} />
          </div>
          <SessionAnalyticsChart
            metric="active-users"
            title="Active Users"
            initialData={data}
            startDate={startDate}
            endDate={endDate}
            today={today}
          />
          <div className="flex justify-end">
            <Button
              type="button"
              variant="outline"
              onClick={() =>
                downloadCsv(
                  "User and Behavior Analysis",
                  dailySummary.map((row) => ({
                    Date: row.date,
                    "Active Users": row.activeUsers,
                  })),
                )
              }
            >
              Export CSV
            </Button>
          </div>
        </section>
      ) : (
        <ReportNoData title="Active Users unavailable" />
      )}
      {newUsersError ? (
        <ReportUnavailable title="New User Growth unavailable" error={newUsersError} />
      ) : newUsersData ? (
        <SessionAnalyticsChart
          metric="new-users"
          title="New User Growth"
          initialData={newUsersData}
          startDate={newUsersStartDate}
          endDate={newUsersEndDate}
          today={today}
        />
      ) : (
        <ReportNoData title="New User Growth unavailable" />
      )}
      {returningUsersError ? (
        <ReportUnavailable
          title="Returning Users unavailable"
          error={returningUsersError}
        />
      ) : returningUsersData ? (
        <SessionAnalyticsChart
          metric="returning-users"
          title="Returning Users by Frequency"
          initialData={returningUsersData}
          startDate={startDate}
          endDate={endDate}
          today={today}
        />
      ) : (
        <ReportNoData title="Returning Users unavailable" />
      )}
      {meanChargingError ? (
        <ReportUnavailable
          title="Mean Charging unavailable"
          error={meanChargingError}
        />
      ) : meanChargingData ? (
        <SessionAnalyticsChart
          metric="mean-charging"
          title="Mean Charging Duration by Charger Type"
          initialData={meanChargingData}
          startDate={startDate}
          endDate={endDate}
          today={today}
        />
      ) : (
        <ReportNoData title="Mean Charging unavailable" />
      )}
    </div>
  );
}

function ReportUnavailable({
  title,
  error,
}: {
  title: string;
  error: string;
}) {
  const router = useRouter();

  return (
    <Panel title={title}>
      <div className="flex flex-col items-center gap-3 p-8 text-center">
        <p role="alert" className="text-sm text-destructive">
          {error}
        </p>
        <p className="text-sm text-muted-foreground">
          Could not load analytics for these dates.
        </p>
        <Button type="button" variant="outline" onClick={() => router.refresh()}>
          Retry
        </Button>
      </div>
    </Panel>
  );
}

function ReportNoData({ title }: { title: string }) {
  return (
    <Panel title={title}>
      <p role="alert" className="p-8 text-center text-muted-foreground">
        The analytics report returned no usable data.
      </p>
    </Panel>
  );
}

export function AnalyticsLiveDashboard(props: Props) {
  const isRevenue = props.report === "revenue";
  const title = isRevenue ? "Revenue & Cost Analysis" : "User & Behavior Analysis";
  const description = isRevenue
    ? "Live, network-wide session revenue and cost. Each chart has independent filters."
    : "Live, network-wide session activity. Each chart has independent filters.";

  return (
    <div className="space-y-5">
      <PageHeader title={title} />
      <p className="text-sm text-muted-foreground">{description}</p>
      {props.report === "revenue" ? (
        <div className="space-y-6">
          {props.revenueError ? (
            <ReportUnavailable
              title="Revenue unavailable"
              error={props.revenueError}
            />
          ) : props.revenueData ? (
            <RevenueReport
              data={props.revenueData}
              startDate={props.startDate}
              endDate={props.endDate}
              today={props.today}
            />
          ) : (
            <ReportNoData title="Revenue unavailable" />
          )}
          {props.costError ? (
            <ReportUnavailable title="Cost unavailable" error={props.costError} />
          ) : props.costData ? (
            <CostReport
              data={props.costData}
              startDate={props.startDate}
              endDate={props.endDate}
              today={props.today}
            />
          ) : (
            <ReportNoData title="Cost unavailable" />
          )}
        </div>
      ) : (
        <ActiveUsersReport
          data={props.data}
          error={props.error}
          returningUsersData={props.returningUsersData}
          returningUsersError={props.returningUsersError}
          meanChargingData={props.meanChargingData}
          meanChargingError={props.meanChargingError}
          newUsersData={props.newUsersData}
          newUsersError={props.newUsersError}
          newUsersStartDate={props.newUsersStartDate}
          newUsersEndDate={props.newUsersEndDate}
          startDate={props.startDate}
          endDate={props.endDate}
          today={props.today}
        />
      )}
    </div>
  );
}
