import { ChevronDown, ChevronRight } from "lucide-react";
import { DataTable } from "@/components/datatable/data-table";
import type { ColumnDef } from "@tanstack/react-table";
import type { TableRow, TabType } from "@/types/asset-settings";
import { extractAssetClassParts } from "@/utils/asset-settings-utils";
import { PRIMARY_COLOR } from "@/lib/common";

const EXPAND_COLLAPSE_BTN_CLASS =
  "rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50 transition-colors";

export interface AssetTableViewProps {
  groupedAssets: Record<string, TableRow[]>;
  expandedClasses: Set<string>;
  onToggleClass: (className: string) => void;
  onExpandAll: () => void;
  onCollapseAll: () => void;
  filteredColumns: ColumnDef<any>[];
  classTotals: Record<
    string,
    { purchase: number; market: number; gainLoss: number }
  >;
  activeTab: TabType;
}

const DEFAULT_CLASS_TOTALS = { purchase: 0, market: 0, gainLoss: 0 };

export function AssetTableView({
  groupedAssets,
  expandedClasses,
  onToggleClass,
  onExpandAll,
  onCollapseAll,
  filteredColumns,
  classTotals,
  activeTab: _activeTab,
}: AssetTableViewProps) {
  return (
    <div className="space-y-4">
      <div className="flex gap-2 mb-4">
        <button onClick={onExpandAll} className={EXPAND_COLLAPSE_BTN_CLASS}>
          Expand All
        </button>
        <button onClick={onCollapseAll} className={EXPAND_COLLAPSE_BTN_CLASS}>
          Collapse All
        </button>
      </div>

      {Object.entries(groupedAssets).map(([className, assets]) => {
        const isExpanded = expandedClasses.has(className);
        const totals = classTotals[className] ?? DEFAULT_CLASS_TOTALS;

        return (
          <div
            key={className}
            className="rounded-lg border border-slate-200 bg-white shadow-sm overflow-hidden"
          >
            <div
              className="flex items-center justify-between px-6 py-4 bg-slate-50 hover:bg-slate-100 cursor-pointer transition-colors border-b border-slate-200"
              onClick={() => onToggleClass(className)}
            >
              <div className="flex items-center gap-3">
                {isExpanded ? (
                  <ChevronDown className="h-5 w-5" style={{ color: PRIMARY_COLOR }} />
                ) : (
                  <ChevronRight className="h-5 w-5" style={{ color: PRIMARY_COLOR }} />
                )}
                <h3 className="text-lg font-semibold text-slate-900">
                  {className}
                </h3>
                <span className="text-sm text-slate-500">
                  ({assets.length} assets)
                </span>
              </div>
            </div>

            {isExpanded && (
              <div className="p-4">
                <DataTable columns={filteredColumns} data={assets} />
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}
