"use client";

import { useState, useMemo } from "react";
import { DataTable } from "@/components/datatable/data-table";
import { columns } from "@/components/datatable/listdepositsreport/columns";
import { PageHeader } from "@/components/ui/PageHeader";
import { RefreshCw, Filter } from "lucide-react";
import { ReportFilters } from "@/components/ui/ReportFilters";
import { useDepositReport } from "@/hooks/useDepositReport";
import { StatCards } from "@/components/reports/common/StatCards";
import { DownloadButton } from "@/components/reports/common/DownloadButton";

const actionButtonClass = (disabled: boolean) =>
  disabled
    ? "inline-flex items-center gap-1 rounded-lg border border-gray-200 bg-gray-100 px-2 py-1 text-xs font-medium text-gray-500 shadow-sm transition-all duration-200 cursor-not-allowed"
    : "inline-flex items-center gap-1 rounded-lg border border-[#428B4D]/40 bg-white px-2 py-1 text-xs font-semibold text-slate-700 shadow-sm transition-all duration-200 hover:-translate-y-0.5 hover:border-[#428B4D] hover:bg-[#428B4D] hover:text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-[#428B4D]/40 active:scale-95";

export default function DepositReport() {
  const {
    data,
    totals,
    availableCurrencies,
    availableBanks,
    selectedBanks,
    selectedCurrencies,
    setSelectedBanks,
    setSelectedCurrencies,
    loading,
    loadData,
  } = useDepositReport();

  const [highlighted, setHighlighted] = useState<string | null>(null);
  const [showFilters, setShowFilters] = useState(false);

  const getActiveFilterCount = () => {
    let count = 0;
    const totalBanks = availableBanks.length;
    if (totalBanks > 0 && selectedBanks.length > 0 && selectedBanks.length < totalBanks) {
      count++;
    }
    const totalCurrencies = availableCurrencies.length;
    if (totalCurrencies > 0 && selectedCurrencies.length > 0 && selectedCurrencies.length < totalCurrencies) {
      count++;
    }
    return count;
  };

  const currencies = useMemo(() => {
    return Object.keys(totals).sort();
  }, [totals]);

  const helperTextMap = useMemo(() => {
    const map: Record<string, string> = {};
    currencies.forEach(code => {
      map[code] = `${code} Details`;
    });
    return map;
  }, [currencies]);

  const downloadBody = useMemo(() => {
    const filters: Record<string, string> = {};
    if (selectedBanks.length > 0) {
      filters.bank_id = selectedBanks.join('|');
    }
    if (selectedCurrencies.length > 0) {
      filters.currency = selectedCurrencies.join('|');
    }
    return filters;
  }, [selectedBanks, selectedCurrencies]);

  return (
    <div className="container mx-auto px-4 mt-6">
      <PageHeader
        title="Deposit Report"
        description="View all deposit transactions and details."
        breadcrumbs={[
          { label: "Home", href: "/" },
          { label: "Cash" },
          { label: "Deposits" },
          { label: "Report" },
        ]}
        actions={
          <div className="flex items-center gap-2">
            <button
              onClick={() => setShowFilters(!showFilters)}
              className={`inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 text-xs font-semibold shadow-sm transition-all duration-200 ${
                showFilters
                  ? "border-[#428B4D] bg-[#428B4D] text-white"
                  : "border-[#428B4D]/40 bg-white text-slate-700 hover:bg-[#428B4D] hover:text-white"
              }`}
            >
              <Filter className="h-4 w-4" />
              Filters {getActiveFilterCount() > 0 && `(${getActiveFilterCount()})`}
            </button>
            <button
              onClick={() => loadData()}
              disabled={loading}
              className={actionButtonClass(loading)}
            >
              <RefreshCw size={16} className={loading ? "animate-spin" : ""} />
              {loading ? "Refreshing..." : "Refresh"}
            </button>
          </div>
        }
      />

      {/* Filter Panel */}
      {showFilters && (
        <div className="mt-6">
          <ReportFilters
            filters={[
              {
                type: "search-multi-select",
                label: "Banks",
                options: availableBanks.map((bank) => ({
                  id: bank.bank_id,
                  label: bank.bank_name,
                  value: bank.bank_id,
                })),
                value: selectedBanks,
                onChange: (value) => setSelectedBanks(value),
              },
              {
                type: "search-multi-select",
                label: "Currencies",
                options: availableCurrencies.map((currency) => ({
                  id: currency.currency_id,
                  label: currency.code,
                  value: currency.currency_id,
                })),
                value: selectedCurrencies,
                onChange: (value) => setSelectedCurrencies(value),
              },
            ]}
            onApply={() => {
              loadData();
              setShowFilters(false);
            }}
            onReset={() => {
              const allBankIds = availableBanks.map((bank) => bank.bank_id);
              const allCurrencyIds = availableCurrencies.map((currency) => currency.currency_id);
              setSelectedBanks(allBankIds);
              setSelectedCurrencies(allCurrencyIds);
              // Need to reload data after resetting filters
              setTimeout(() => loadData(), 0);
            }}
            variant="panel"
            showFilters={true}
          />
        </div>
      )}

      {currencies.length > 0 && (
        <StatCards
          totals={totals}
          currencies={currencies}
          highlighted={highlighted}
          onHighlight={setHighlighted}
          loading={loading}
          className="mb-8"
          helperTextMap={helperTextMap}
        />
      )}

      <DownloadButton
        endpoint="/api/reports/liquidity/deposit"
        filenamePrefix="OXYFINZ-Deposit-Report"
        body={downloadBody}
        className="mb-4"
      />

      <DataTable columns={columns} data={data} />
    </div>
  );
}