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

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 [expandedNotes, setExpandedNotes] = React.useState<Record<string, boolean>>({});
  const { holdingsWithNotes } = usePortfolioNotes(portfolio.holdings, true);

  const totalGainPositive = portfolio.totalGain >= 0;
  const dayChangePositive = portfolio.dayChange >= 0;

  const toggleNotesExpanded = (symbol: string) => {
    setExpandedNotes((prev) => ({
      ...prev,
      [symbol]: !prev[symbol],
    }));
  };

  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-term-border-subtle 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-term-text">Portfolio Overview</h2>
            <p className="mt-1 text-[11px] font-mono text-term-text-muted">
              Review positions, run portfolio commands, and open trade workflows from here.
            </p>
          </div>
          <div className="text-[11px] font-mono text-term-text-tertiary">
            {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-term-text">
            Holdings ({portfolio.holdings.length})
          </h3>
          <button
            type="button"
            className="text-[11px] font-mono text-term-text-muted transition-colors hover:text-term-text"
            onClick={() => onRunCommand('/portfolio')}
          >
            Reload overview
          </button>
        </div>
        {portfolio.holdings.length === 0 ? (
          <div className="flex flex-col items-center justify-center rounded-lg border border-term-border bg-term-surface px-6 py-12">
            <div className="mb-4 text-info">
              <Package className="h-12 w-12" />
            </div>
            <div className="mb-2 text-lg font-mono text-term-text">No holdings yet</div>
            <div className="mb-6 max-w-md text-center text-sm font-mono text-term-text-muted">
              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="sticky top-0 bg-term-surface text-term-text-muted">
                <tr className="border-b border-term-border-subtle">
                  <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-center text-[10px] uppercase tracking-wider">
                    Research
                  </th>
                  <th className="px-4 py-2 text-right text-[10px] uppercase tracking-wider">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-term-border-subtle">
                {holdingsWithNotes.map((holding, index) => {
                  const gainPositive = holding.gainLoss >= 0;
                  const isExpanded = expandedNotes[holding.symbol] || false;
                  const hasNotes = (holding.notesCount ?? 0) > 0;

                  return (
                    <React.Fragment key={holding.symbol}>
                      <tr
                        className="transition-all duration-150 hover:bg-term-highlight hover:shadow-sm"
                        style={{ animationDelay: `${index * 30}ms` }}
                      >
                        <td className="px-4 py-3">
                          <button
                            type="button"
                            className="text-left transition-colors hover:text-info"
                            onClick={() => onSelectHolding?.(holding.symbol)}
                          >
                            <div className="font-semibold text-term-text">{holding.symbol}</div>
                            <div className="text-[10px] text-term-text-muted">{holding.name}</div>
                          </button>
                        </td>
                        <td className="px-4 py-3 text-right text-term-text">
                          {formatQuantity(holding.quantity)}
                        </td>
                        <td className="px-4 py-3 text-right text-term-text">
                          {formatCurrency(holding.avgCost)}
                        </td>
                        <td className="px-4 py-3 text-right text-term-text">
                          {formatCurrency(holding.currentPrice)}
                        </td>
                        <td className="px-4 py-3 text-right text-term-text">
                          {formatCurrency(holding.currentValue)}
                        </td>
                        <td
                          className={`px-4 py-3 text-right font-semibold ${
                            gainPositive ? 'text-positive' : 'text-negative'
                          }`}
                        >
                          {formatSignedCurrency(holding.gainLoss)}
                          <div className="text-[10px]">
                            ({gainPositive ? '+' : ''}
                            {holding.gainLossPercent.toFixed(2)}%)
                          </div>
                        </td>
                        <td className="px-4 py-3 text-center">
                          {hasNotes ? (
                            <button
                              type="button"
                              onClick={() => toggleNotesExpanded(holding.symbol)}
                              className="mx-auto flex items-center justify-center gap-1 text-xs text-info transition-colors hover:text-term-text"
                            >
                              {isExpanded ? (
                                <ChevronDown className="w-3 h-3" />
                              ) : (
                                <ChevronRight className="w-3 h-3" />
                              )}
                              <span>{holding.notesCount} notes</span>
                            </button>
                          ) : (
                            <span className="text-[10px] text-term-text-tertiary">No research</span>
                          )}
                        </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>
                      {isExpanded && hasNotes && (
                        <tr className="bg-term-elevated">
                          <td colSpan={8} className="px-4 py-3">
                            <div className="space-y-2">
                              <div className="mb-2 text-[10px] uppercase tracking-wide text-term-text-muted">
                                Recent Research Notes
                              </div>
                              {holding.recentNotes?.map((note) => (
                                <div
                                  key={note.id}
                                  className="flex items-start gap-2 rounded border border-term-border-subtle bg-term-highlight p-2 transition-colors hover:border-term-border"
                                >
                                  <FileText className="mt-0.5 h-3 w-3 flex-shrink-0 text-info" />
                                  <div className="flex-1 min-w-0">
                                    <div className="flex items-center gap-2 mb-1">
                                      <span className="rounded bg-term-bg px-1.5 py-0.5 text-[10px] font-mono text-info">
                                        {note.noteType.replace(/_/g, ' ')}
                                      </span>
                                      <EvidenceStatusBadge status={note.evidenceStatus} />
                                    </div>
                                    <div className="line-clamp-2 text-xs text-term-text">
                                      {note.title}
                                    </div>
                                  </div>
                                </div>
                              ))}
                              <ActionButton
                                onClick={() => onRunCommand(`/research ${holding.symbol}`)}
                                size="sm"
                                className="w-full"
                              >
                                View all research for {holding.symbol}
                              </ActionButton>
                            </div>
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </DataSection>
    </div>
  );
};

const EvidenceStatusBadge: React.FC<{ status: string }> = ({ status }) => {
  const colors: Record<string, string> = {
    unsourced: 'bg-term-highlight text-term-text-muted',
    source_linked: 'bg-[var(--term-status-info)] text-info',
    quoted: 'bg-[var(--term-status-info)] text-[var(--term-status-info-strong)]',
    corroborated: 'bg-[var(--term-status-success)] text-positive',
    inferred: 'bg-warning/10 text-warning',
    contradicted: 'bg-[var(--term-status-error)] text-negative',
    stale: 'bg-[var(--term-status-warning)] text-warning',
    superseded: 'bg-term-highlight text-term-text-muted',
  };

  const colorClass = colors[status] || colors.unsourced;

  return (
    <span className={`text-[10px] font-mono px-1.5 py-0.5 rounded ${colorClass}`}>
      {status.replace(/_/g, ' ')}
    </span>
  );
};
