"use client";

import { useEffect, useMemo, useRef } from "react";
import { ColumnDef, DataTableLayout } from "ikoncomponents";
import { useAppCache } from "@/app/utils/context/AppCacheContext";

export interface FXRateData {
  id: string;
  year: string;
  currency: string;
  fxRate: number;
  activeStatus: boolean;
}

function FXRateDataTable() {
  // FX rate data comes from the shared app-wide cache.
  const { fxRateResponse, isLoading, refresh } = useAppCache();

  const fxRateTableData = useMemo<FXRateData[]>(() => {
    const rows: FXRateData[] = [];
    (fxRateResponse?.content || []).forEach((item: any) => {
      const fxRateDetails = item.fxRateDetails || {};
      Object.values(fxRateDetails).forEach((yearGroup: any) => {
        Object.values(yearGroup).forEach((detail: any) => {
          rows.push({
            id: detail.id,
            year: detail.year,
            currency: detail.currency,
            fxRate: detail.fxRate,
            activeStatus: detail.activeStatus,
          });
        });
      });
    });
    return rows;
  }, [fxRateResponse]);

  // This table is list-only, so hide DataTableLayout's built-in List/Grid toggle
  // (it has no prop to disable it). Once mounted we find the grid button and hide
  // the whole toggle group, so a lone list button isn't left dangling.
  const tableContainerRef = useRef<HTMLDivElement>(null);
  const hidGridToggle = useRef(false);

  useEffect(() => {
    if (isLoading || hidGridToggle.current) return;
    const gridButton =
      tableContainerRef.current?.querySelector<HTMLButtonElement>(
        'button[title="Grid View"]',
      );
    if (gridButton?.parentElement) {
      gridButton.parentElement.style.display = "none";
      hidGridToggle.current = true;
    }
  }, [isLoading]);

  const columns: ColumnDef<FXRateData>[] = [
    {
      accessorKey: "year",
      header: "Year",
      cell: (row) => <span>{row.year ?? "n/a"}</span>,
    },
    {
      accessorKey: "currency",
      header: "Currency",
      cell: (row) => <span>{row.currency ?? "n/a"}</span>,
    },
    {
      accessorKey: "fxRate",
      header: "FX Rate",
      cell: (row) => <span>{row.fxRate ?? "n/a"}</span>,
    },
    {
      accessorKey: "activeStatus",
      header: "Status",
      cell: (row) => (
        <span>{row.activeStatus ? "Active" : "Inactive"}</span>
      ),
    },
  ];

  return (
    <div ref={tableContainerRef}>
      <DataTableLayout
        data={fxRateTableData}
        columns={columns}
        extraTools={{
          keyExtractor: (row: FXRateData) => row.id,
          totalPages: 1,
          currentPage: 1,
          isLoading,
          onReload: refresh,
        }}
      />
    </div>
  );
}

export default FXRateDataTable;
