"use client";

import { useState, useCallback, useMemo } from "react";
import { RefreshCw } from "lucide-react";
import { PageHeader } from "@/components/ui/PageHeader";
import { ErrorMessage } from "@/components/ui/ErrorMessage";
import { useCashDetailsReport } from "@/hooks/useCashDetailsReport";
import { StatCards } from "@/components/reports/common/StatCards";
import { DownloadButton } from "@/components/reports/common/DownloadButton";
import { CashDetailsTable } from "@/components/reports/cashdetails/CashDetailsTable";
import { CashDetailsReportActions } from "@/components/reports/cashdetails/CashDetailsReportActions";
import { BREADCRUMBS } from "@/constants/breadcrumbs";
import {
  REPORT_PAGE_CONTAINER,
  REPORT_PAGE_CONTAINER_ALT,
  REPORT_PRIMARY,
} from "@/app/reports/constants";
import { getUniqueCurrencyCodes } from "@/app/reports/utils";

export default function CashDetailsReport() {
  const { data, loading, error, fetchReport, clearError } =
    useCashDetailsReport();
  const [highlighted, setHighlighted] = useState<string | null>(null);

  const currencies = useMemo(
    () => getUniqueCurrencyCodes(data?.detail_items),
    [data?.detail_items]
  );

  const handleRefresh = useCallback(() => fetchReport(), [fetchReport]);

  if (loading) {
    return (
      <div className={REPORT_PAGE_CONTAINER_ALT}>
        <PageHeader
          title="Cash Details Report"
          description="Loading…"
          breadcrumbs={[...BREADCRUMBS.cashDetailsLiquidity]}
        />
        <div className="flex h-64 items-center justify-center">
          <RefreshCw
            className="h-8 w-8 animate-spin"
            style={{ color: REPORT_PRIMARY }}
          />
        </div>
      </div>
    );
  }

  return (
    <div className={REPORT_PAGE_CONTAINER}>
      <PageHeader
        title="Cash Details Report"
        breadcrumbs={[...BREADCRUMBS.cashDetailsLiquidity]}
        actions={
          <CashDetailsReportActions
            isLoading={loading}
            onRefresh={handleRefresh}
          />
        }
      />

      {error && (
        <ErrorMessage
          error={error}
          onDismiss={clearError}
          className="mt-6"
        />
      )}

      <StatCards
        totals={data?.totals?.amount_array_total}
        currencies={currencies}
        highlighted={highlighted}
        onHighlight={setHighlighted}
      />

      <DownloadButton
        endpoint="/api/reports/liquidity/cashdetails"
        filenamePrefix="Cash_Details_Report"
      />

      <CashDetailsTable
        data={data}
        highlighted={highlighted}
        onHighlight={setHighlighted}
      />
    </div>
  );
}
