import React from 'react';
import { Package } from 'lucide-react';
import { Portfolio } from '../../types/financial';
import { PortfolioAction, PortfolioActionSeed } from '../../types/terminal';
import { MetricGrid, ActionButton, ButtonGroup, DataSection } from '../ui';

interface PortfolioPanelProps {
  portfolio: Portfolio;
  onRunCommand: (command: string) => void;
  onStartAction: (action: PortfolioAction, seed?: PortfolioActionSeed) => void;
  onSelectHolding?: (symbol: string) => void;
}

const formatCurrency = (value: number) =>
  `$${value.toLocaleString('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;

const formatSignedCurrency = (value: number) =>
  `${value >= 0 ? '+' : '-'}${formatCurrency(Math.abs(value))}`;

const formatQuantity = (value: number) => {
  const rendered = value.toFixed(4);
  return rendered.replace(/\.?0+$/, '');
};

export const PortfolioPanel: React.FC<PortfolioPanelProps> = ({
  portfolio,
  onRunCommand,
  onStartAction,
  onSelectHolding,
}) => {
  const totalGainPositive = portfolio.totalGain >= 0;
  const dayChangePositive = portfolio.dayChange >= 0;

  const summaryMetrics = [
    {
      label: 'Total Value',
      value: formatCurrency(portfolio.totalValue),
      size: 'lg' as const,
    },
    {
      label: "Today's Change",
      value: `${dayChangePositive ? '+' : ''}${formatCurrency(Math.abs(portfolio.dayChange))} (${dayChangePositive ? '+' : ''}${portfolio.dayChangePercent.toFixed(2)}%)`,
      sentiment: (dayChangePositive ? 'positive' : 'negative') as 'positive' | 'negative',
    },
    {
      label: 'Unrealized Gain/Loss',
      value: `${totalGainPositive ? '+' : ''}${formatCurrency(Math.abs(portfolio.totalGain))} (${totalGainPositive ? '+' : ''}${portfolio.totalGainPercent.toFixed(2)}%)`,
      sentiment: (totalGainPositive ? 'positive' : 'negative') as 'positive' | 'negative',
    },
    {
      label: 'Cash Balance',
      value: formatCurrency(portfolio.cashBalance ?? 0),
    },
    {
      label: 'Realized Gain',
      value: formatCurrency(portfolio.realizedGain ?? 0),
      sentiment:
        ((portfolio.realizedGain ?? 0) >= 0 ? 'positive' : 'negative') as 'positive' | 'negative',
    },
    {
      label: 'Holdings',
      value: String(portfolio.holdingsCount ?? portfolio.holdings.length),
    },
  ];

  return (
    <div className="portfolio-panel min-w-0 max-w-full overflow-y-auto py-4">
      <header className="mb-6 flex flex-col gap-4 border-b border-[#1a1a1a] pb-4">
        <div className="flex flex-col gap-2 lg:flex-row lg:items-end lg:justify-between">
          <div>
            <h2 className="text-heading-lg text-[#e0e0e0]">Portfolio Overview</h2>
            <p className="mt-1 text-[11px] font-mono text-[#888888]">
              Review positions, run portfolio commands, and open trade workflows from here.
            </p>
          </div>
          <div className="text-[11px] font-mono text-[#666666]">
            {portfolio.stalePricingSymbols?.length
              ? `Stale pricing fallback: ${portfolio.stalePricingSymbols.join(', ')}`
              : 'Live pricing loaded'}
          </div>
        </div>

        <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
          <ButtonGroup>
            <ActionButton onClick={() => onStartAction('buy')}>Buy</ActionButton>
            <ActionButton onClick={() => onStartAction('sell')}>Sell</ActionButton>
            <ActionButton onClick={() => onStartAction('deposit')}>Deposit</ActionButton>
            <ActionButton onClick={() => onStartAction('withdraw')}>Withdraw</ActionButton>
          </ButtonGroup>
          <ButtonGroup>
            <ActionButton onClick={() => onRunCommand('/portfolio stats')} size="sm">
              Stats
            </ActionButton>
            <ActionButton onClick={() => onRunCommand('/portfolio history')} size="sm">
              History
            </ActionButton>
          </ButtonGroup>
        </div>
      </header>

      <DataSection divider="none" padding="sm">
        <MetricGrid metrics={summaryMetrics} columns={3} />
      </DataSection>

      <DataSection divider="top" padding="sm">
        <div className="mb-4 flex items-center justify-between">
          <h3 className="text-heading-sm text-[#e0e0e0]">
            Holdings ({portfolio.holdings.length})
          </h3>
          <button
            type="button"
            className="text-[11px] font-mono text-[#888888] transition-colors hover:text-[#e0e0e0]"
            onClick={() => onRunCommand('/portfolio')}
          >
            Reload overview
          </button>
        </div>
        {portfolio.holdings.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 px-6 border border-[#1f1f1f] bg-[#111111] rounded-lg">
            <div className="text-[#58a6ff] mb-4">
              <Package className="h-12 w-12" />
            </div>
            <div className="text-lg font-mono text-[#e0e0e0] mb-2">No holdings yet</div>
            <div className="text-sm font-mono text-[#888888] mb-6 text-center max-w-md">
              Start by depositing cash, then buy your first position to begin tracking your portfolio.
            </div>
            <ButtonGroup>
              <ActionButton onClick={() => onStartAction('deposit')} variant="primary">
                Deposit cash
              </ActionButton>
              <ActionButton onClick={() => onStartAction('buy')}>Buy first company</ActionButton>
            </ButtonGroup>
          </div>
        ) : (
          <div className="max-w-full overflow-x-auto">
            <table className="min-w-[720px] w-full text-sm font-mono">
              <thead className="bg-[#111111] text-[#888888] sticky top-0">
                <tr className="border-b border-[#1a1a1a]">
                  <th className="px-4 py-2 text-left text-[10px] uppercase tracking-wider">
                    Symbol
                  </th>
                  <th className="px-4 py-2 text-right text-[10px] uppercase tracking-wider">
                    Qty
                  </th>
                  <th className="px-4 py-2 text-right text-[10px] uppercase tracking-wider">
                    Avg Cost
                  </th>
                  <th className="px-4 py-2 text-right text-[10px] uppercase tracking-wider">
                    Current
                  </th>
                  <th className="px-4 py-2 text-right text-[10px] uppercase tracking-wider">
                    Value
                  </th>
                  <th className="px-4 py-2 text-right text-[10px] uppercase tracking-wider">
                    Gain/Loss
                  </th>
                  <th className="px-4 py-2 text-right text-[10px] uppercase tracking-wider">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[#1a1a1a]">
                {portfolio.holdings.map((holding, index) => {
                  const gainPositive = holding.gainLoss >= 0;

                  return (
                    <tr
                      key={holding.symbol}
                      className="transition-all duration-150 hover:bg-[#151515] hover:shadow-sm"
                      style={{ animationDelay: `${index * 30}ms` }}
                    >
                      <td className="px-4 py-3">
                        <button
                          type="button"
                          className="text-left transition-colors hover:text-[#58a6ff]"
                          onClick={() => onSelectHolding?.(holding.symbol)}
                        >
                          <div className="font-semibold text-[#e0e0e0]">{holding.symbol}</div>
                          <div className="text-[10px] text-[#888888]">{holding.name}</div>
                        </button>
                      </td>
                      <td className="px-4 py-3 text-right text-[#e0e0e0]">
                        {formatQuantity(holding.quantity)}
                      </td>
                      <td className="px-4 py-3 text-right text-[#e0e0e0]">
                        {formatCurrency(holding.avgCost)}
                      </td>
                      <td className="px-4 py-3 text-right text-[#e0e0e0]">
                        {formatCurrency(holding.currentPrice)}
                      </td>
                      <td className="px-4 py-3 text-right text-[#e0e0e0]">
                        {formatCurrency(holding.currentValue)}
                      </td>
                      <td
                        className={`px-4 py-3 text-right font-semibold ${
                          gainPositive ? 'text-[#00d26a]' : 'text-[#ff4757]'
                        }`}
                      >
                        {formatSignedCurrency(holding.gainLoss)}
                        <div className="text-[10px]">
                          ({gainPositive ? '+' : ''}
                          {holding.gainLossPercent.toFixed(2)}%)
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex justify-end gap-2">
                          <ActionButton
                            onClick={() => onStartAction('sell', { symbol: holding.symbol })}
                            size="sm"
                          >
                            Sell
                          </ActionButton>
                          <ActionButton
                            onClick={() => onRunCommand(`/search ${holding.symbol}`)}
                            size="sm"
                          >
                            Search
                          </ActionButton>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </DataSection>
    </div>
  );
};
