import { useState, useEffect } from 'react';
import { Sun, TrendingUp, TrendingDown, Calendar, AlertCircle, Newspaper, BarChart3 } from 'lucide-react';

interface MarketSummary {
  date: string;
  sentiment: 'BULLISH' | 'BEARISH' | 'NEUTRAL';
  priceAction: {
    current: number;
    open: number;
    high: number;
    low: number;
    change: number;
    changePercent: number;
  };
  keyLevels: {
    resistance: number[];
    support: number[];
    pivot: number;
  };
  economicEvents: Array<{
    time: string;
    event: string;
    impact: 'HIGH' | 'MEDIUM' | 'LOW';
    forecast?: string;
  }>;
  newsSummary: {
    bullishCount: number;
    bearishCount: number;
    topHeadlines: string[];
  };
  aiPrediction: {
    direction: 'UP' | 'DOWN' | 'SIDEWAYS';
    confidence: number;
    keyFactors: string[];
  };
}

interface DailyMarketSummaryProps {
  currentPrice: number;
}

export default function DailyMarketSummary({ currentPrice }: DailyMarketSummaryProps) {
  const [summary, setSummary] = useState<MarketSummary>({
    date: new Date().toDateString(),
    sentiment: 'NEUTRAL',
    priceAction: {
      current: currentPrice,
      open: currentPrice - 5,
      high: currentPrice + 10,
      low: currentPrice - 12,
      change: 5,
      changePercent: 0.25,
    },
    keyLevels: {
      resistance: [currentPrice + 20, currentPrice + 40, currentPrice + 60],
      support: [currentPrice - 20, currentPrice - 40, currentPrice - 60],
      pivot: currentPrice,
    },
    economicEvents: [
      { time: '08:30', event: 'US CPI Data', impact: 'HIGH', forecast: '0.3%' },
      { time: '10:00', event: 'Fed Speech', impact: 'HIGH' },
      { time: '14:00', event: 'Gold Inventory', impact: 'MEDIUM' },
    ],
    newsSummary: {
      bullishCount: 12,
      bearishCount: 8,
      topHeadlines: [
        'Dollar weakens amid Fed rate cut expectations',
        'Geopolitical tensions boost safe-haven demand',
        'Central banks continue gold accumulation',
      ],
    },
    aiPrediction: {
      direction: 'UP',
      confidence: 72,
      keyFactors: [
        'Weakening dollar trend',
        'Strong technical support holding',
        'Bullish news sentiment',
        'Upcoming high-impact economic data',
      ],
    },
  });

  const [selectedView, setSelectedView] = useState<'overview' | 'levels' | 'events' | 'ai'>('overview');

  // Update summary when price changes significantly
  useEffect(() => {
    setSummary(prev => ({
      ...prev,
      priceAction: {
        ...prev.priceAction,
        current: currentPrice,
        change: currentPrice - prev.priceAction.open,
        changePercent: ((currentPrice - prev.priceAction.open) / prev.priceAction.open) * 100,
      },
    }));
  }, [currentPrice]);

  const getSentimentColor = (sentiment: string) => {
    switch (sentiment) {
      case 'BULLISH': return 'text-green-500';
      case 'BEARISH': return 'text-red-500';
      default: return 'text-gray-400';
    }
  };

  const getImpactColor = (impact: string) => {
    switch (impact) {
      case 'HIGH': return 'bg-red-500/20 text-red-500';
      case 'MEDIUM': return 'bg-yellow-500/20 text-yellow-500';
      case 'LOW': return 'bg-blue-500/20 text-blue-500';
      default: return 'bg-gray-500/20 text-gray-500';
    }
  };

  const views = [
    { id: 'overview', label: 'Overview', icon: Sun },
    { id: 'levels', label: 'Key Levels', icon: BarChart3 },
    { id: 'events', label: 'Events', icon: Calendar },
    { id: 'ai', label: 'AI Forecast', icon: TrendingUp },
  ];

  return (
    <div className="h-full flex flex-col">
      {/* Header */}
      <div className="mb-4 pb-4 border-b border-gray-700">
        <div className="flex items-center gap-3 mb-3">
          <Sun className="w-6 h-6 text-gold-500" />
          <div>
            <h3 className="text-lg font-semibold">Daily Market Brief</h3>
            <p className="text-xs text-gray-400">
              {new Date().toLocaleDateString('en-US', { 
                weekday: 'long', 
                month: 'long', 
                day: 'numeric', 
                year: 'numeric' 
              })}
            </p>
          </div>
        </div>

        {/* Quick Stats */}
        <div className="grid grid-cols-2 gap-3">
          <div className="p-3 bg-dark-hover rounded-lg">
            <div className="text-xs text-gray-400 mb-1">Current Price</div>
            <div className="text-xl font-bold text-white">
              ${summary.priceAction.current.toFixed(2)}
            </div>
            <div className={`text-sm font-medium ${
              summary.priceAction.change >= 0 ? 'text-green-500' : 'text-red-500'
            }`}>
              {summary.priceAction.change >= 0 ? '+' : ''}
              ${summary.priceAction.change.toFixed(2)} ({summary.priceAction.changePercent.toFixed(2)}%)
            </div>
          </div>
          <div className="p-3 bg-dark-hover rounded-lg">
            <div className="text-xs text-gray-400 mb-1">Market Sentiment</div>
            <div className={`text-xl font-bold ${getSentimentColor(summary.sentiment)}`}>
              {summary.sentiment}
            </div>
            <div className="text-sm text-gray-400">
              {summary.newsSummary.bullishCount} 🟢 / {summary.newsSummary.bearishCount} 🔴
            </div>
          </div>
        </div>
      </div>

      {/* View Selector */}
      <div className="flex gap-1 mb-4 p-1 bg-dark-bg rounded-lg">
        {views.map(view => {
          const Icon = view.icon;
          return (
            <button
              key={view.id}
              onClick={() => setSelectedView(view.id as any)}
              className={`flex-1 px-3 py-2 rounded-lg transition-colors text-sm ${
                selectedView === view.id
                  ? 'bg-gold-500 text-black font-medium'
                  : 'text-gray-400 hover:text-white'
              }`}
            >
              <Icon className="w-4 h-4 mx-auto mb-1" />
              {view.label}
            </button>
          );
        })}
      </div>

      {/* Content Area */}
      <div className="flex-1 overflow-y-auto">
        {/* Overview */}
        {selectedView === 'overview' && (
          <div className="space-y-4">
            {/* Price Range */}
            <div className="p-4 bg-dark-hover rounded-lg">
              <h4 className="font-semibold mb-3 flex items-center gap-2">
                <BarChart3 className="w-4 h-4 text-blue-500" />
                Today's Range
              </h4>
              <div className="grid grid-cols-3 gap-3 text-sm">
                <div>
                  <div className="text-gray-400 text-xs mb-1">Open</div>
                  <div className="font-semibold">${summary.priceAction.open.toFixed(2)}</div>
                </div>
                <div>
                  <div className="text-gray-400 text-xs mb-1">High</div>
                  <div className="font-semibold text-green-500">${summary.priceAction.high.toFixed(2)}</div>
                </div>
                <div>
                  <div className="text-gray-400 text-xs mb-1">Low</div>
                  <div className="font-semibold text-red-500">${summary.priceAction.low.toFixed(2)}</div>
                </div>
              </div>
            </div>

            {/* Top Headlines */}
            <div className="p-4 bg-dark-hover rounded-lg">
              <h4 className="font-semibold mb-3 flex items-center gap-2">
                <Newspaper className="w-4 h-4 text-blue-500" />
                Top Headlines
              </h4>
              <div className="space-y-2">
                {summary.newsSummary.topHeadlines.map((headline, i) => (
                  <div key={i} className="flex items-start gap-2 text-sm">
                    <div className="w-1.5 h-1.5 rounded-full bg-gold-500 mt-1.5 flex-shrink-0" />
                    <div className="text-gray-300">{headline}</div>
                  </div>
                ))}
              </div>
            </div>

            {/* Quick AI Insight */}
            <div className={`p-4 rounded-lg border-2 ${
              summary.aiPrediction.direction === 'UP'
                ? 'bg-green-500/10 border-green-500/30'
                : summary.aiPrediction.direction === 'DOWN'
                ? 'bg-red-500/10 border-red-500/30'
                : 'bg-gray-500/10 border-gray-500/30'
            }`}>
              <div className="flex items-center gap-2 mb-2">
                {summary.aiPrediction.direction === 'UP' ? (
                  <TrendingUp className="w-5 h-5 text-green-500" />
                ) : (
                  <TrendingDown className="w-5 h-5 text-red-500" />
                )}
                <div>
                  <div className="font-semibold">AI Prediction: {summary.aiPrediction.direction}</div>
                  <div className="text-xs text-gray-400">
                    Confidence: {summary.aiPrediction.confidence}%
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Key Levels */}
        {selectedView === 'levels' && (
          <div className="space-y-4">
            <div className="p-4 bg-dark-hover rounded-lg">
              <h4 className="font-semibold mb-3 text-green-500">Resistance Levels</h4>
              <div className="space-y-2">
                {summary.keyLevels.resistance.map((level, i) => (
                  <div key={i} className="flex items-center justify-between p-2 bg-green-500/5 rounded border border-green-500/20">
                    <span className="text-sm text-gray-400">R{i + 1}</span>
                    <span className="font-semibold">${level.toFixed(2)}</span>
                    <span className="text-xs text-gray-500">
                      +{((level - currentPrice) / currentPrice * 100).toFixed(2)}%
                    </span>
                  </div>
                ))}
              </div>
            </div>

            <div className="p-4 bg-dark-hover rounded-lg border-2 border-gold-500/30">
              <h4 className="font-semibold mb-2 text-gold-500">Pivot Point</h4>
              <div className="text-center">
                <div className="text-2xl font-bold">${summary.keyLevels.pivot.toFixed(2)}</div>
                <div className="text-xs text-gray-400">Key decision level</div>
              </div>
            </div>

            <div className="p-4 bg-dark-hover rounded-lg">
              <h4 className="font-semibold mb-3 text-red-500">Support Levels</h4>
              <div className="space-y-2">
                {summary.keyLevels.support.map((level, i) => (
                  <div key={i} className="flex items-center justify-between p-2 bg-red-500/5 rounded border border-red-500/20">
                    <span className="text-sm text-gray-400">S{i + 1}</span>
                    <span className="font-semibold">${level.toFixed(2)}</span>
                    <span className="text-xs text-gray-500">
                      {((level - currentPrice) / currentPrice * 100).toFixed(2)}%
                    </span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* Economic Events */}
        {selectedView === 'events' && (
          <div className="space-y-3">
            <div className="flex items-center gap-2 mb-2">
              <Calendar className="w-5 h-5 text-blue-500" />
              <h4 className="font-semibold">Today's Economic Calendar</h4>
            </div>
            {summary.economicEvents.map((event, i) => (
              <div key={i} className="p-4 bg-dark-hover rounded-lg border border-gray-700">
                <div className="flex items-start justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <div className="w-12 h-12 rounded-lg bg-blue-500/20 flex items-center justify-center">
                      <span className="text-sm font-bold text-blue-500">{event.time}</span>
                    </div>
                    <div>
                      <div className="font-semibold">{event.event}</div>
                      {event.forecast && (
                        <div className="text-xs text-gray-400">Forecast: {event.forecast}</div>
                      )}
                    </div>
                  </div>
                  <span className={`px-2 py-1 rounded text-xs font-medium ${getImpactColor(event.impact)}`}>
                    {event.impact}
                  </span>
                </div>
              </div>
            ))}

            <div className="p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg mt-4">
              <div className="flex items-center gap-2 text-yellow-500 text-sm">
                <AlertCircle className="w-4 h-4" />
                <span>Be cautious during high-impact events</span>
              </div>
            </div>
          </div>
        )}

        {/* AI Forecast */}
        {selectedView === 'ai' && (
          <div className="space-y-4">
            <div className="p-4 bg-gradient-to-br from-purple-500/20 to-blue-500/20 rounded-lg border border-purple-500/30">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-12 h-12 rounded-lg bg-purple-500/30 flex items-center justify-center">
                  {summary.aiPrediction.direction === 'UP' ? (
                    <TrendingUp className="w-6 h-6 text-green-500" />
                  ) : (
                    <TrendingDown className="w-6 h-6 text-red-500" />
                  )}
                </div>
                <div>
                  <div className="text-xl font-bold">
                    {summary.aiPrediction.direction}WARD Bias
                  </div>
                  <div className="text-sm text-gray-400">
                    AI Confidence: {summary.aiPrediction.confidence}%
                  </div>
                </div>
              </div>

              {/* Confidence Bar */}
              <div className="mb-4">
                <div className="w-full bg-gray-700 rounded-full h-3">
                  <div
                    className={`h-3 rounded-full transition-all ${
                      summary.aiPrediction.confidence > 70
                        ? 'bg-green-500'
                        : summary.aiPrediction.confidence > 50
                        ? 'bg-yellow-500'
                        : 'bg-red-500'
                    }`}
                    style={{ width: `${summary.aiPrediction.confidence}%` }}
                  />
                </div>
              </div>
            </div>

            {/* Key Factors */}
            <div className="p-4 bg-dark-hover rounded-lg">
              <h4 className="font-semibold mb-3">Key Contributing Factors</h4>
              <div className="space-y-2">
                {summary.aiPrediction.keyFactors.map((factor, i) => (
                  <div key={i} className="flex items-start gap-2">
                    <div className="w-6 h-6 rounded-full bg-gold-500/20 flex items-center justify-center flex-shrink-0 mt-0.5">
                      <span className="text-xs font-bold text-gold-500">{i + 1}</span>
                    </div>
                    <div className="text-sm text-gray-300">{factor}</div>
                  </div>
                ))}
              </div>
            </div>

            <div className="p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg">
              <div className="text-xs text-blue-400">
                <strong>Disclaimer:</strong> AI predictions are based on historical patterns and current data. Always use proper risk management and make your own trading decisions.
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
