"use client";

import { Checkbox } from "@/components/ui/checkbox";
import type { LedgerTransaction, AssetTypeOption } from "@/types/ocr";
import {
  getTransactionTypeColor,
  getChangeClass,
  ASSET_TYPE_OPTIONS,
  VALID_SAVE_TRANSACTION_TYPES,
} from "@/types/ocr";

/** Map any case variant of asset type to the proper AssetTypeOption */
function normalizeAssetType(value: string | undefined): AssetTypeOption | "" {
  if (!value) return "";
  const lower = value.toLowerCase();
  const map: Record<string, AssetTypeOption> = {
    stock: "Stock",
    equity: "Stock",
    structure: "Structure",
    bond: "Bond",
    bondfund: "BondFund",
    bondfunds: "BondFund",
    cash: "Cash",
    leverage: "Leverage",
  };
  return map[lower] || "";
}

interface LedgerTransactionsTableProps {
  transactions: LedgerTransaction[];
  periodIndex: number;
  selectedTransactions: Set<string>;
  assetTypeOverrides: Record<string, AssetTypeOption>;
  onToggleTransaction: (id: string) => void;
  onSetAssetType: (id: string, value: AssetTypeOption) => void;
  onToggleAll?: (periodIndex: number, selectAll: boolean) => void;
}

export function LedgerTransactionsTable({
  transactions,
  periodIndex,
  selectedTransactions,
  assetTypeOverrides,
  onToggleTransaction,
  onSetAssetType,
  onToggleAll,
}: LedgerTransactionsTableProps) {
  if (!transactions || transactions.length === 0) {
    return (
      <div className="px-4 py-6 text-center text-gray-400 text-xs">
        No transactions in this period.
      </div>
    );
  }

  // Calculate select-all state for this period
  const selectableIds: string[] = [];
  transactions.forEach((trans, tIdx) => {
    if (VALID_SAVE_TRANSACTION_TYPES.includes(trans.TransactionType)) {
      selectableIds.push(`${periodIndex}_${tIdx}`);
    }
  });
  const allSelected =
    selectableIds.length > 0 &&
    selectableIds.every((id) => selectedTransactions.has(id));
  const someSelected =
    !allSelected && selectableIds.some((id) => selectedTransactions.has(id));

  return (
    <div className="overflow-x-auto" style={{ scrollbarWidth: "thin", scrollbarColor: "#d1d5db transparent" }}>
      <table className="w-full text-xs border-collapse">
        <thead>
          <tr className="bg-gray-50 border-b">
            <th className="px-2 py-2 text-left font-medium text-gray-600 whitespace-nowrap">
              Type
            </th>
            <th className="px-2 py-2 text-left font-medium text-gray-600 whitespace-nowrap">
              ISIN
            </th>
            <th className="px-2 py-2 text-left font-medium text-gray-600 whitespace-nowrap">
              Name
            </th>
            <th className="px-2 py-2 text-center font-medium text-gray-600 whitespace-nowrap">
              <div className="flex items-center justify-center gap-1.5">
                <Checkbox
                  checked={allSelected ? true : someSelected ? "indeterminate" : false}
                  onCheckedChange={() => onToggleAll?.(periodIndex, !allSelected)}
                  className="h-3.5 w-3.5 cursor-pointer active:scale-90"
                />
                <span>Add to DB</span>
              </div>
            </th>
            <th className="px-2 py-2 text-left font-medium text-gray-600 whitespace-nowrap">
              Asset Type
            </th>
            <th className="px-2 py-2 text-right font-medium text-gray-600 whitespace-nowrap">
              Current Price
            </th>
            <th className="px-2 py-2 text-right font-medium text-gray-600 whitespace-nowrap">
              Market Price
            </th>
            <th className="px-2 py-2 text-right font-medium text-gray-600 whitespace-nowrap">
              Qty Change
            </th>
            <th className="px-2 py-2 text-right font-medium text-gray-600 whitespace-nowrap">
              Price Change
            </th>
            <th className="px-2 py-2 text-right font-medium text-gray-600 whitespace-nowrap">
              Qty Diff
            </th>
            <th className="px-2 py-2 text-right font-medium text-gray-600 whitespace-nowrap">
              PV Diff
            </th>
            <th className="px-2 py-2 text-right font-medium text-gray-600 whitespace-nowrap">
              MV Diff
            </th>
            <th className="px-2 py-2 text-right font-medium text-gray-600 whitespace-nowrap">
              WA Price
            </th>
            <th className="px-2 py-2 text-right font-medium text-gray-600 whitespace-nowrap">
              Value Change
            </th>
          </tr>
        </thead>
        <tbody>
          {transactions.map((trans, tIdx) => {
            const id = `${periodIndex}_${tIdx}`;
            const isSelected = selectedTransactions.has(id);
            const canSelect = VALID_SAVE_TRANSACTION_TYPES.includes(
              trans.TransactionType
            );
            const assetType =
              assetTypeOverrides[id] ||
              normalizeAssetType(trans.Type) ||
              normalizeAssetType(trans.CurrentAClass) ||
              "";
            const marketPrice =
              trans.position?.original?.MarketPrice ||
              trans.position?.original?.market_price ||
              "";

            return (
              <tr
                key={tIdx}
                className={`border-b hover:bg-gray-50 transition-colors ${
                  isSelected ? "bg-blue-50" : ""
                }`}
              >
                <td className="px-2 py-1.5">
                  <span
                    className={`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium ${getTransactionTypeColor(
                      trans.TransactionType
                    )}`}
                  >
                    {trans.TransactionType}
                  </span>
                </td>
                <td className="px-2 py-1.5 text-gray-700 whitespace-nowrap">
                  {trans.ISIN || ""}
                </td>
                <td className="px-2 py-1.5 text-gray-700 max-w-[150px] truncate">
                  {trans.Name || ""}
                </td>
                <td className="px-2 py-1.5 text-center">
                  {canSelect && (
                    <div className="flex justify-center">
                      <Checkbox
                        checked={isSelected}
                        onCheckedChange={() => onToggleTransaction(id)}
                        className="h-3.5 w-3.5 cursor-pointer active:scale-90"
                      />
                    </div>
                  )}
                </td>
                <td className="px-2 py-1.5">
                  {canSelect && (
                    <select
                      value={assetType}
                      onChange={(e) =>
                        onSetAssetType(id, e.target.value as AssetTypeOption)
                      }
                      className="w-20 px-1 py-0.5 border rounded text-[10px] focus:outline-none"
                    >
                      <option value="">--</option>
                      {ASSET_TYPE_OPTIONS.map((opt) => (
                        <option key={opt} value={opt}>
                          {opt}
                        </option>
                      ))}
                    </select>
                  )}
                </td>
                <td className="px-2 py-1.5 text-right text-gray-700 whitespace-nowrap">
                  {trans.CurrentPurchasePrice || "0.00"}
                </td>
                <td className="px-2 py-1.5 text-right text-gray-700 whitespace-nowrap">
                  {marketPrice || "0.00"}
                </td>
                <td
                  className={`px-2 py-1.5 text-right whitespace-nowrap ${getChangeClass(
                    trans.QuantityChange
                  )}`}
                >
                  {trans.QuantityChange || "0.00"}
                </td>
                <td
                  className={`px-2 py-1.5 text-right whitespace-nowrap ${getChangeClass(
                    trans.PurchasePriceChange
                  )}`}
                >
                  {trans.PurchasePriceChange || "0.00"}
                </td>
                <td
                  className={`px-2 py-1.5 text-right whitespace-nowrap ${getChangeClass(
                    trans.QtyDiff
                  )}`}
                >
                  {trans.QtyDiff || "0.00"}
                </td>
                <td
                  className={`px-2 py-1.5 text-right whitespace-nowrap ${getChangeClass(
                    trans.PVDiff
                  )}`}
                >
                  {trans.PVDiff || "0.00"}
                </td>
                <td
                  className={`px-2 py-1.5 text-right whitespace-nowrap ${getChangeClass(
                    trans.MVDiff
                  )}`}
                >
                  {trans.MVDiff || "0.00"}
                </td>
                <td className="px-2 py-1.5 text-right text-gray-700 whitespace-nowrap">
                  {trans.WAPrice || "N/A"}
                </td>
                <td
                  className={`px-2 py-1.5 text-right whitespace-nowrap ${getChangeClass(
                    trans.ValueChange
                  )}`}
                >
                  {trans.ValueChange || "N/A"}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
