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-[#1a1a1a] px-4 py-4 transition-colors hover:border-[#58a6ff]">
        <div className="flex items-center gap-2 mb-3">
          <div className="text-[#58a6ff]">
            <Wallet className="h-4 w-4" />
          </div>
          <div className="text-[10px] font-mono uppercase tracking-wider text-[#888888]">
            Portfolio
          </div>
        </div>
        <div className="text-xs font-mono text-[#666666] 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-[#1a1a1a] transition-colors hover:border-[#58a6ff]">
      <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-[#888888]">
              Portfolio
            </h4>
            <span className="text-[10px] font-mono text-[#666666]">
              ({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-[#00d26a]' : 'text-[#ff4757]'
              }`}
            >
              {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-[#666666]">
                <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-[#e0e0e0]">
            {formatCurrency(portfolio.totalValue)}
          </span>
          <span
            className={`text-xs font-mono transition-colors duration-200 ${
              isPositive ? 'text-[#00d26a]' : 'text-[#ff4757]'
            }`}
          >
            {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-[#1a1a1a] hover:pl-4 border-l-2 border-transparent hover:border-[#58a6ff]"
              style={{ animationDelay: `${index * 50}ms` }}
            >
              <div className="flex items-center gap-2">
                <span className="font-mono text-[#e0e0e0] transition-colors group-hover:text-[#58a6ff]">
                  {holding.symbol}
                </span>
                <span className="text-[10px] text-[#888888]">
                  {holding.quantity} {holding.quantity === 1 ? 'share' : 'shares'}
                </span>
              </div>
              <span
                className={`font-mono transition-colors duration-150 ${
                  holdingPositive ? 'text-[#00d26a]' : 'text-[#ff4757]'
                }`}
              >
                {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-[#888888] transition-colors hover:text-[#e0e0e0] hover:bg-[#1a1a1a] 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-[#888888] transition-colors hover:text-[#e0e0e0] hover:bg-[#1a1a1a] rounded"
          >
            Show less
          </button>
        ) : null}
      </div>
    </div>
  );
};
