import React from "react";
import { ChevronDown, ChevronUp, ChevronRight } from "lucide-react";
import { ConsolidatedData } from "@/hooks/useConsolidatedHoldingsReport";

interface DetailedHoldingsTableProps {
  data: ConsolidatedData;
  expandedAssetClasses: Set<string>;
  expandedAssetTypes: Set<string>;
  onToggleAssetClass: (name: string) => void;
  onToggleAssetType: (key: string) => void;
  onExpandAll: () => void;
  onCollapseAll: () => void;
  onExpandAllForAssetClass: (name: string) => void;
  onCollapseAllForAssetClass: (name: string) => void;
  isAllExpanded: boolean;
}

export const DetailedHoldingsTable: React.FC<DetailedHoldingsTableProps> = ({
  data,
  expandedAssetClasses,
  expandedAssetTypes,
  onToggleAssetClass,
  onToggleAssetType,
  onExpandAll,
  onCollapseAll,
  onExpandAllForAssetClass,
  onCollapseAllForAssetClass,
  isAllExpanded,
}) => {
  return (
    <div className="mb-6 rounded-lg border border-slate-200 bg-white shadow-sm overflow-hidden text-slate-900">
      <div className="bg-slate-50 border-b border-slate-200 px-6 py-4">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-semibold text-slate-900">Detailed Holdings</h3>
          <button
            onClick={isAllExpanded ? onCollapseAll : onExpandAll}
            className="inline-flex items-center gap-2 rounded-lg px-3 py-1.5 text-xs font-medium border border-slate-300 bg-white text-slate-700 hover:bg-slate-50 transition-colors"
          >
            {isAllExpanded ? (
              <>
                <ChevronUp className="h-4 w-4" />
                Collapse All
              </>
            ) : (
              <>
                <ChevronDown className="h-4 w-4" />
                Expand All
              </>
            )}
          </button>
        </div>
      </div>

      <div className="overflow-x-auto max-h-[600px] overflow-y-auto relative">
        <table className="w-full text-sm min-w-[800px]">
          <thead className="sticky top-0 z-40">
            <tr className="bg-slate-50 border-b-2 border-slate-300">
              <th className="text-left px-6 py-3 font-semibold text-slate-700 bg-slate-50 whitespace-nowrap">Type</th>
              <th className="text-right px-6 py-3 font-semibold text-slate-700 bg-slate-50 whitespace-nowrap">Purchase Value</th>
              <th className="text-right px-6 py-3 font-semibold text-slate-700 bg-slate-50 whitespace-nowrap">XIRR</th>
              <th className="text-right px-6 py-3 font-semibold text-slate-700 bg-slate-50 whitespace-nowrap">Market Value with Interest</th>
              <th className="text-right px-6 py-3 font-semibold text-slate-700 bg-slate-50 whitespace-nowrap">% of Portfolio</th>
            </tr>
          </thead>
          <tbody>
            {data.asset_classes.map((assetClass, acIdx) => {
              const isClassOpen = expandedAssetClasses.has(assetClass.name);
              const hasInterest = parseFloat(assetClass.market_value_without_interest.replace(/,/g, '')) !==
                parseFloat(assetClass.market_value.replace(/,/g, ''));
              return (
                <React.Fragment key={acIdx}>
                  <tr
                    className="border-b-2 border-slate-300 sticky z-30 cursor-pointer hover:bg-slate-50"
                    style={{
                      top: '43px',
                      backgroundColor: '#ffffff'
                    }}
                    onClick={() => onToggleAssetClass(assetClass.name)}
                  >
                    <td className="px-6 py-3 bg-white">
                      <div className="flex items-center justify-between gap-2">
                        <div className="flex items-center gap-2 font-bold text-slate-900">
                          {isClassOpen ? (
                            <ChevronDown className="h-5 w-5 text-[#428B4D] flex-shrink-0" />
                          ) : (
                            <ChevronRight className="h-5 w-5 text-[#428B4D] flex-shrink-0" />
                          )}
                          <span>{assetClass.name}</span>
                        </div>
                        {isClassOpen && assetClass.asset_types.length > 0 && (() => {
                          const allTypesExpanded = assetClass.asset_types.every((_, atIdx) =>
                            expandedAssetTypes.has(`${assetClass.name}-${atIdx}`)
                          );
                          return (
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                if (allTypesExpanded) {
                                  onCollapseAllForAssetClass(assetClass.name);
                                } else {
                                  onExpandAllForAssetClass(assetClass.name);
                                }
                              }}
                              className="inline-flex items-center gap-1 rounded px-2 py-1 text-xs font-medium border border-slate-300 bg-white text-slate-700 hover:bg-slate-50"
                            >
                              {allTypesExpanded ? (
                                <>
                                  <ChevronUp className="h-3 w-3" />
                                  <span>Collapse All</span>
                                </>
                              ) : (
                                <>
                                  <ChevronDown className="h-3 w-3" />
                                  <span>Expand All</span>
                                </>
                              )}
                            </button>
                          );
                        })()}
                      </div>
                    </td>
                    <td className="text-right px-6 py-3 font-bold text-slate-900 bg-white whitespace-nowrap">
                      {data.currency_code} {assetClass.purchase_value}
                    </td>
                    <td className="text-right px-6 py-3 font-bold text-slate-900 bg-white">--</td>
                    <td className="text-right px-6 py-3 font-bold text-slate-900 bg-white whitespace-nowrap">
                      <div>{data.currency_code} {assetClass.market_value}</div>
                      {hasInterest && (
                        <div className="text-xs font-normal text-slate-600 mt-1">
                          Without Interest: {assetClass.market_value_without_interest}
                        </div>
                      )}
                    </td>
                    <td className="text-right px-6 py-3 font-bold text-slate-900 bg-white whitespace-nowrap">
                      {assetClass.percent_of_portfolio}%
                    </td>
                  </tr>

                  {isClassOpen && assetClass.asset_types.map((assetType, atIdx) => {
                    const typeKey = `${assetClass.name}-${atIdx}`;
                    const isTypeOpen = expandedAssetTypes.has(typeKey);
                    return (
                      <React.Fragment key={typeKey}>
                        <tr
                          className="border-b-2 border-slate-300 cursor-pointer sticky z-20 hover:bg-slate-100"
                          style={{
                            top: '105px',
                            backgroundColor: '#e2e8f0'
                          }}
                          onClick={() => onToggleAssetType(typeKey)}
                        >
                          <td className="px-8 py-3 font-semibold text-slate-900 bg-slate-200">
                            <div className="flex items-center gap-2">
                              {isTypeOpen ? (
                                <ChevronDown className="h-4 w-4 text-slate-700 flex-shrink-0" />
                              ) : (
                                <ChevronRight className="h-4 w-4 text-slate-700 flex-shrink-0" />
                              )}
                              <span>{assetType.name || "Uncategorized"}</span>
                            </div>
                          </td>
                          <td className="text-right px-6 py-3 font-semibold text-slate-900 bg-slate-200 whitespace-nowrap">
                            {data.currency_code} {assetType.purchase_value}
                          </td>
                          <td className="text-right px-6 py-3 font-semibold text-slate-900 bg-slate-200">--</td>
                          <td className="text-right px-6 py-3 font-semibold text-slate-900 bg-slate-200 whitespace-nowrap">
                            {data.currency_code} {assetType.market_value}
                          </td>
                          <td className="text-right px-6 py-3 font-semibold text-slate-900 bg-slate-200 whitespace-nowrap">
                            {assetType.percent_of_asset_class}%
                          </td>
                        </tr>

                        {isTypeOpen && (
                          <tr>
                            <td colSpan={5} className="p-0">
                              <div>
                                <table className="w-full text-sm bg-white border-l-4 border-[#428B4D]/30 min-w-[1200px]">
                                  <thead className="sticky z-10" style={{ top: '150px' }}>
                                    <tr className="bg-slate-50 border-b-2 border-slate-200">
                                      <th className="text-left px-12 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">Quantity</th>
                                      <th className="text-left px-4 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">Ticker / Name</th>
                                      <th className="text-center px-4 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">Currency</th>
                                      <th className="text-right px-4 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">Purchase Value</th>
                                      <th className="text-right px-4 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">Weighted Avg Cost</th>
                                      <th className="text-right px-4 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">Real Price</th>
                                      <th className="text-right px-4 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">Market Price</th>
                                      <th className="text-right px-4 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">Market Value</th>
                                      <th className="text-right px-4 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">Interest</th>
                                      <th className="text-right px-4 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">Total Gain / Loss</th>
                                      <th className="text-right px-4 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">Market Value RC</th>
                                      <th className="text-right px-4 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">XIRR %</th>
                                      <th className="text-right px-4 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">% of Asset</th>
                                      <th className="text-right px-4 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">% of Asset Class</th>
                                      <th className="text-right px-4 py-3 font-semibold text-xs text-slate-700 bg-slate-50 whitespace-nowrap">% of Portfolio</th>
                                    </tr>
                                  </thead>
                                  <tbody>
                                    {assetType.holdings.map((holding, hIdx) => (
                                      <tr key={hIdx} className="hover:bg-slate-50 border-t border-slate-100">
                                        <td className="px-12 py-2 text-right text-slate-900 whitespace-nowrap">{holding.quantity}</td>
                                        <td className="px-4 py-2 min-w-[150px]">
                                          <div className="font-medium uppercase text-slate-600 text-xs">
                                            {holding.ticker}
                                          </div>
                                          {holding.name && (
                                            <div className="text-xs text-slate-800 mt-0.5">
                                              {holding.name}
                                            </div>
                                          )}
                                        </td>
                                        <td className="text-center px-4 py-2 text-slate-900 whitespace-nowrap">{holding.currency}</td>
                                        <td className="text-right px-4 py-2 text-slate-900 whitespace-nowrap">{holding.purchase_value}</td>
                                        <td className="text-right px-4 py-2 text-slate-900 whitespace-nowrap">{holding.weighted_avg_cost}</td>
                                        <td className="text-right px-4 py-2 text-slate-900 whitespace-nowrap">{holding.real_price}</td>
                                        <td className="text-right px-4 py-2 text-slate-900 whitespace-nowrap">{holding.market_price}</td>
                                        <td className="text-right px-4 py-2 text-slate-900 whitespace-nowrap">{holding.market_value}</td>
                                        <td className="text-right px-4 py-2 text-slate-900 whitespace-nowrap">{holding.interest}</td>
                                        <td className={`text-right px-4 py-2 font-medium whitespace-nowrap ${
                                          parseFloat(holding.total_gain_loss.replace(/,/g, '')) >= 0
                                            ? 'text-green-600'
                                            : 'text-red-600'
                                        }`}>
                                          {holding.total_gain_loss}
                                        </td>
                                        <td className="text-right px-4 py-2 text-slate-900 whitespace-nowrap">{holding.market_value_rc}</td>
                                        <td className="text-right px-4 py-2 text-slate-900 whitespace-nowrap">{holding.xirr || '--'}</td>
                                        <td className="text-right px-4 py-2 text-slate-900 whitespace-nowrap">{holding.percent_of_asset_type}%</td>
                                        <td className="text-right px-4 py-2 text-slate-900 whitespace-nowrap">{holding.percent_of_asset_class}%</td>
                                        <td className="text-right px-4 py-2 text-slate-900 whitespace-nowrap">{holding.percent_of_portfolio}%</td>
                                      </tr>
                                    ))}
                                  </tbody>
                                </table>
                              </div>
                            </td>
                          </tr>
                        )}
                      </React.Fragment>
                    );
                  })}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};
