import {
  getAdminRevenueAnalytics,
  getAdminTicketSalesAnalytics,
  getAdminAttendanceAnalytics,
  getAdminEventPerformanceAnalytics,
  getAdminParticipantAnalytics,
} from "@/lib/api/admin";
import { resolveDateRange, computeDelta, fillDailySeries } from "@/lib/date-range";
import { formatCompactCurrency } from "@/lib/format";
import { MetricCard } from "@/components/ui/metric-card";
import { DateRangeFilter } from "@/components/ui/date-range-filter";
import { ExportDropdown } from "@/components/ui/export-dropdown";
import { AdminRevenueTrendChart } from "@/components/analytics/admin-revenue-trend-chart";
import { AdminTicketTypeChart } from "@/components/analytics/admin-ticket-type-chart";
import { AdminAttendanceProgress } from "@/components/analytics/admin-attendance-progress";
import { AdminEventPerformanceTable } from "@/components/analytics/admin-event-performance-table";
import { AdminAnalyticsEmptyState } from "@/components/analytics/admin-analytics-empty-state";

type SearchParams = Promise<{ range?: string; start?: string; end?: string }>;

export default async function AdminAnalyticsPage({ searchParams }: { searchParams: SearchParams }) {
  const params = await searchParams;
  const { rangeKey, current, previous } = resolveDateRange(params);

  const currentQuery = { start_date: current.start, end_date: current.end };
  const previousQuery = { start_date: previous.start, end_date: previous.end };

  const [
    revenueRes,
    prevRevenueRes,
    ticketSalesRes,
    prevTicketSalesRes,
    attendanceRes,
    prevAttendanceRes,
    participantsRes,
    prevParticipantsRes,
    eventsRes,
  ] = await Promise.all([
    getAdminRevenueAnalytics(currentQuery),
    getAdminRevenueAnalytics(previousQuery),
    getAdminTicketSalesAnalytics(currentQuery),
    getAdminTicketSalesAnalytics(previousQuery),
    getAdminAttendanceAnalytics(currentQuery),
    getAdminAttendanceAnalytics(previousQuery),
    getAdminParticipantAnalytics(currentQuery),
    getAdminParticipantAnalytics(previousQuery),
    getAdminEventPerformanceAnalytics(currentQuery),
  ]);

  const totalRevenue = Number(revenueRes.data.total_revenue);
  const totalSold = ticketSalesRes.data.total_sold;
  const totalParticipants = participantsRes.data.total_participants;
  const overallRate = attendanceRes.data.overall_rate;

  const hasData = totalRevenue > 0 || totalSold > 0 || totalParticipants > 0;

  // Export dropdown targets the "Performa Event" table — the most complete
  // dataset on this consolidated page. No backend endpoint exports every
  // metric in one file, and adding one is a backend change out of scope here.
  const exportQuery = `start_date=${current.start}&end_date=${current.end}`;

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <h2 className="text-2xl font-bold">Analytics</h2>
          <p className="mt-1 text-sm text-kolabora-neutral-dark/60">Platform performance overview</p>
        </div>
        <div className="flex flex-col items-start gap-3 sm:items-end">
          <DateRangeFilter rangeKey={rangeKey} currentStart={current.start} currentEnd={current.end} />
          <ExportDropdown baseUrl="/api/admin/analytics/events/export" query={exportQuery} />
        </div>
      </div>

      {!hasData ? (
        <AdminAnalyticsEmptyState />
      ) : (
        <>
          <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
            <MetricCard
              label="Total Pendapatan"
              value={formatCompactCurrency(totalRevenue)}
              delta={computeDelta(totalRevenue, Number(prevRevenueRes.data.total_revenue))}
            />
            <MetricCard
              label="Tickets Sold"
              value={totalSold.toLocaleString("en-US")}
              delta={computeDelta(totalSold, prevTicketSalesRes.data.total_sold)}
            />
            <MetricCard
              label="Total Participants"
              value={totalParticipants.toLocaleString("en-US")}
              delta={computeDelta(totalParticipants, prevParticipantsRes.data.total_participants)}
            />
            <MetricCard
              label="Tingkat Kehadiran"
              value={`${overallRate.toLocaleString("en-US")}%`}
              delta={computeDelta(overallRate, prevAttendanceRes.data.overall_rate)}
            />
          </div>

          <AdminRevenueTrendChart data={fillDailySeries(revenueRes.data.daily, current)} />

          <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
            <AdminTicketTypeChart data={ticketSalesRes.data.by_ticket_type} />
            <AdminAttendanceProgress data={attendanceRes.data.by_event} />
          </div>

          <AdminEventPerformanceTable data={eventsRes.data} />
        </>
      )}
    </div>
  );
}
