import React, { useState } from 'react';
import { ChevronDown, TrendingDown, TrendingUp, Wallet } from 'lucide-react';
import { Portfolio } from '../../types/financial';
import { ActionButton } from '../ui';

interface PortfolioSummaryProps {
  portfolio: Portfolio | null;
  onLoadPortfolio: () => void;
}

export const PortfolioSummary: React.FC<PortfolioSummaryProps> = ({
  portfolio,
  onLoadPortfolio,
}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const initialHoldingsCount = 3;

  const formatCurrency = (value: number) => {
    if (Math.abs(value) >= 1000) {
      return `$${(value / 1000).toFixed(1)}K`;
    }
    return `$${value.toFixed(0)}`;
  };

  if (!portfolio) {
    return (
      <div className="border-l-2 border-term-border-subtle px-4 py-4 transition-colors hover:border-info">
        <div className="flex items-center gap-2 mb-3">
          <div className="text-info">
            <Wallet className="h-4 w-4" />
          </div>
          <div className="text-[10px] font-mono uppercase tracking-wider text-term-text-tertiary">
            Portfolio
          </div>
        </div>
        <div className="text-xs font-mono text-term-text-muted mb-4">
          Load your latest portfolio snapshot
        </div>
        <ActionButton onClick={onLoadPortfolio} className="w-full">
          Load portfolio
        </ActionButton>
      </div>
    );
  }

  const isPositive = portfolio.dayChange >= 0;
  const visibleHoldings = isExpanded
    ? portfolio.holdings
    : portfolio.holdings.slice(0, initialHoldingsCount);
  const hasMoreHoldings = portfolio.holdings.length > initialHoldingsCount;

  return (
    <div className="border-l-2 border-term-border-subtle transition-colors hover:border-info">
      <button
        onClick={() => {
          setIsExpanded((current) => !current);
        }}
        className="w-full px-3 py-2 text-left"
        aria-expanded={isExpanded}
      >
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <h4 className="text-[10px] font-mono uppercase tracking-wider text-term-text-tertiary">
              Portfolio
            </h4>
            <span className="text-[10px] font-mono text-term-text-muted">
              ({portfolio.holdings.length} positions)
            </span>
          </div>
          <div className="flex items-center gap-2">
            <div
              className={`flex items-center gap-1 transition-transform duration-200 ${
                isPositive ? 'text-positive' : 'text-negative'
              }`}
            >
              {isPositive ? (
                <TrendingUp className="h-3 w-3" />
              ) : (
                <TrendingDown className="h-3 w-3" />
              )}
              <span className="text-xs font-mono">
                {isPositive ? '+' : ''}
                {portfolio.dayChangePercent.toFixed(1)}%
              </span>
            </div>
            {hasMoreHoldings ? (
              <span className="text-term-text-muted">
                <ChevronDown
                  className={`h-3 w-3 transition-transform duration-200 ${
                    isExpanded ? 'rotate-180' : ''
                  }`}
                />
              </span>
            ) : null}
          </div>
        </div>

        <div className="mt-2 flex items-baseline gap-3">
          <span className="text-sm font-mono font-bold text-term-text">
            {formatCurrency(portfolio.totalValue)}
          </span>
          <span
            className={`text-xs font-mono transition-colors duration-200 ${
              isPositive ? 'text-positive' : 'text-negative'
            }`}
          >
            {isPositive ? '+' : ''}
            {formatCurrency(portfolio.dayChange)} today
          </span>
        </div>
      </button>

      <div
        className="space-y-1 px-3 pb-2"
        style={{
          maxHeight: isExpanded
            ? `${portfolio.holdings.length * 44}px`
            : `${initialHoldingsCount * 44}px`,
          transition: 'max-height 0.3s ease-in-out, opacity 0.2s ease-in-out',
          overflow: 'hidden',
        }}
      >
        {visibleHoldings.map((holding, index) => {
          const holdingPositive = holding.gainLoss >= 0;
          return (
            <button
              key={holding.symbol}
              type="button"
              onClick={onLoadPortfolio}
              className="group flex w-full items-center justify-between rounded-md px-3 py-2 text-xs transition-all duration-150 hover:bg-term-highlight hover:pl-4 border-l-2 border-transparent hover:border-info"
              style={{ animationDelay: `${index * 50}ms` }}
            >
              <div className="flex items-center gap-2">
                <span className="font-mono text-term-text transition-colors group-hover:text-info">
                  {holding.symbol}
                </span>
                <span className="text-[10px] text-term-text-tertiary">
                  {holding.quantity} {holding.quantity === 1 ? 'share' : 'shares'}
                </span>
              </div>
              <span
                className={`font-mono transition-colors duration-150 ${
                  holdingPositive ? 'text-positive' : 'text-negative'
                }`}
              >
                {holdingPositive ? '+' : ''}
                {holding.gainLossPercent.toFixed(1)}%
              </span>
            </button>
          );
        })}

        {hasMoreHoldings && !isExpanded ? (
          <button
            type="button"
            onClick={() => setIsExpanded(true)}
            className="w-full py-1.5 text-center text-[10px] font-mono text-term-text-tertiary transition-colors hover:text-term-text hover:bg-term-highlight rounded"
          >
            See {portfolio.holdings.length - initialHoldingsCount} more positions
          </button>
        ) : null}

        {isExpanded && hasMoreHoldings ? (
          <button
            type="button"
            onClick={() => setIsExpanded(false)}
            className="w-full py-1.5 text-center text-[10px] font-mono text-term-text-tertiary transition-colors hover:text-term-text hover:bg-term-highlight rounded"
          >
            Show less
          </button>
        ) : null}
      </div>
    </div>
  );
};
