import React from 'react';
import { TrendingUp, TrendingDown } from 'lucide-react';
import { TickerHistoryEntry } from '../../types/terminal';

interface TickerHistoryProps {
  history: TickerHistoryEntry[];
  onTickerClick: (symbol: string) => void;
}

const formatTimeAgo = (timestamp: Date): string => {
  const now = new Date();
  const diffMs = now.getTime() - timestamp.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);

  if (diffMins < 1) return 'Just now';
  if (diffMins < 60) return `${diffMins}m ago`;
  if (diffHours < 24) return `${diffHours}h ago`;
  if (diffDays === 1) return 'Yesterday';
  if (diffDays < 7) return `${diffDays}d ago`;
  return timestamp.toLocaleDateString();
};

export const TickerHistory: React.FC<TickerHistoryProps> = ({ history, onTickerClick }) => {
  if (!history || history.length === 0) {
    return (
      <div className="space-y-2">
        <h4 className="text-[10px] font-mono uppercase tracking-wider text-term-text-tertiary px-1">
          Recent Searches
        </h4>
        <div className="text-center py-4 px-2">
          <p className="text-xs text-term-text-muted">No recent searches</p>
          <p className="text-[10px] text-term-text-muted mt-1">
            Use ticker commands like /search, /fa, /news, or /analyze
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between px-1">
        <h4 className="text-[10px] font-mono uppercase tracking-wider text-term-text-tertiary">
          Recent Searches
        </h4>
      </div>

      <div className="space-y-0.5">
        {history.map((entry) => {
          const { company, timestamp } = entry;
          const hasChange = typeof company.changePercent === 'number';
          const isPositive = typeof company.change === 'number' ? company.change >= 0 : false;
          const isLoading = entry.isLoading;

          return (
            <button
              key={company.symbol}
              onClick={() => onTickerClick(company.symbol)}
              className={`w-full text-left px-2 py-2 border-l-2 transition-all group ${
                isLoading
                  ? 'border-[var(--term-status-info-border)] bg-[linear-gradient(90deg,var(--term-status-info),rgb(12_19_26/0.88))]'
                  : 'border-transparent hover:border-info hover:bg-term-highlight'
              }`}
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2 min-w-0 flex-1">
                  <span className="font-mono font-bold text-sm text-term-text group-hover:text-info transition-colors">
                    {company.symbol}
                  </span>
                  {isLoading ? (
                    <div className="flex items-center gap-2 min-w-0 flex-1">
                      <span className="text-[10px] text-term-text-tertiary font-mono uppercase tracking-[0.16em]">
                        syncing
                      </span>
                      <span className="h-2 w-[4.5rem] animate-pulse rounded-full bg-info/20" />
                    </div>
                  ) : (
                    <span className="text-[10px] text-term-text-tertiary truncate">
                      {company.name || company.symbol}
                    </span>
                  )}
                </div>
                <div className="flex items-center gap-2 flex-shrink-0 ml-2">
                  {isLoading ? (
                    <span className="h-3 w-14 animate-pulse rounded-full bg-info/20" />
                  ) : hasChange && (
                    <>
                      <span className={`text-xs font-mono ${isPositive ? 'text-positive' : 'text-negative'}`}>
                        {isPositive ? '+' : ''}{company.changePercent!.toFixed(2)}%
                      </span>
                      {isPositive ? (
                        <TrendingUp className="h-3 w-3 text-positive" />
                      ) : (
                        <TrendingDown className="h-3 w-3 text-negative" />
                      )}
                    </>
                  )}
                </div>
              </div>
              <div className="flex items-center justify-between mt-1">
                {isLoading ? (
                  <span className="h-3 w-20 animate-pulse rounded-full bg-info/20" />
                ) : (
                  <span className="text-xs font-mono text-term-text">
                    {typeof company.price === 'number' ? `$${company.price.toFixed(2)}` : 'Quote pending'}
                  </span>
                )}
                <div className="flex items-center gap-3">
                  {isLoading ? (
                    <>
                      <span className="h-2.5 w-16 animate-pulse rounded-full bg-info/20" />
                      <span className="h-2.5 w-12 animate-pulse rounded-full bg-info/15" />
                    </>
                  ) : typeof company.volume === 'number' && (
                    <span className="text-[10px] text-term-text-muted">
                      Vol: {company.volume.toLocaleString()}
                    </span>
                  )}
                  {!isLoading && (
                    <span className="text-[10px] text-term-text-tertiary">
                      {formatTimeAgo(timestamp)}
                    </span>
                  )}
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
};
