import { useState, useEffect } from 'react';
import { CheckCircle2, Circle, Clock, TrendingUp, Calendar, BarChart3, AlertCircle } from 'lucide-react';

interface ChecklistItem {
  id: string;
  title: string;
  description: string;
  completed: boolean;
  category: 'pre-market' | 'active-trading' | 'post-market';
}

interface DailyChecklistProps {
  onComplete?: (completedCount: number, totalCount: number) => void;
}

const DEFAULT_CHECKLIST: ChecklistItem[] = [
  // Pre-Market (Before Trading)
  {
    id: 'review-calendar',
    title: 'Check Economic Calendar',
    description: 'Review today\'s economic events and their potential impact on gold',
    completed: false,
    category: 'pre-market',
  },
  {
    id: 'check-news',
    title: 'Scan Market News',
    description: 'Read overnight news, geopolitical events, Fed statements',
    completed: false,
    category: 'pre-market',
  },
  {
    id: 'analyze-sentiment',
    title: 'Analyze Market Sentiment',
    description: 'Check overall market sentiment and gold-specific sentiment',
    completed: false,
    category: 'pre-market',
  },
  {
    id: 'identify-levels',
    title: 'Identify Key Levels',
    description: 'Mark support/resistance, pivot points, previous high/low',
    completed: false,
    category: 'pre-market',
  },
  {
    id: 'set-plan',
    title: 'Create Trading Plan',
    description: 'Set daily target, max loss, entry/exit criteria',
    completed: false,
    category: 'pre-market',
  },
  {
    id: 'check-risk',
    title: 'Review Risk Parameters',
    description: 'Confirm position sizing, stop-loss levels, risk per trade',
    completed: false,
    category: 'pre-market',
  },
  {
    id: 'mental-prep',
    title: 'Mental Preparation',
    description: 'Review trading rules, stay disciplined, manage emotions',
    completed: false,
    category: 'pre-market',
  },

  // Active Trading
  {
    id: 'monitor-price',
    title: 'Monitor Price Action',
    description: 'Watch for entry signals based on your plan',
    completed: false,
    category: 'active-trading',
  },
  {
    id: 'follow-plan',
    title: 'Execute According to Plan',
    description: 'Only take trades that match your criteria',
    completed: false,
    category: 'active-trading',
  },
  {
    id: 'manage-positions',
    title: 'Manage Open Positions',
    description: 'Adjust stops, take partials, follow exit rules',
    completed: false,
    category: 'active-trading',
  },
  {
    id: 'track-news-live',
    title: 'Track Breaking News',
    description: 'Monitor for unexpected events that could impact positions',
    completed: false,
    category: 'active-trading',
  },
  {
    id: 'record-trades',
    title: 'Log Trades in Real-Time',
    description: 'Record entry reasons, emotions, and setup quality',
    completed: false,
    category: 'active-trading',
  },

  // Post-Market (After Trading)
  {
    id: 'review-trades',
    title: 'Review All Trades',
    description: 'Analyze winners and losers, identify patterns',
    completed: false,
    category: 'post-market',
  },
  {
    id: 'update-journal',
    title: 'Complete Trading Journal',
    description: 'Document lessons learned, emotional state, market conditions',
    completed: false,
    category: 'post-market',
  },
  {
    id: 'analyze-performance',
    title: 'Analyze Daily Performance',
    description: 'Calculate P&L, win rate, risk-reward, adherence to plan',
    completed: false,
    category: 'post-market',
  },
  {
    id: 'update-levels',
    title: 'Update Key Levels',
    description: 'Mark new support/resistance for tomorrow',
    completed: false,
    category: 'post-market',
  },
  {
    id: 'plan-tomorrow',
    title: 'Preview Tomorrow',
    description: 'Check upcoming economic events and prepare strategy',
    completed: false,
    category: 'post-market',
  },
  {
    id: 'set-alerts',
    title: 'Set Price Alerts',
    description: 'Configure alerts for overnight price movements',
    completed: false,
    category: 'post-market',
  },
];

export default function DailyChecklist({ onComplete }: DailyChecklistProps) {
  const [checklist, setChecklist] = useState<ChecklistItem[]>(() => {
    const stored = localStorage.getItem('daily-trading-checklist');
    if (stored) {
      try {
        return JSON.parse(stored);
      } catch {
        return DEFAULT_CHECKLIST;
      }
    }
    return DEFAULT_CHECKLIST;
  });

  const [activeCategory, setActiveCategory] = useState<'pre-market' | 'active-trading' | 'post-market'>('pre-market');
  const [showCompleted, setShowCompleted] = useState(true);

  // Save to localStorage whenever checklist changes
  useEffect(() => {
    localStorage.setItem('daily-trading-checklist', JSON.stringify(checklist));
    
    const completed = checklist.filter(item => item.completed).length;
    const total = checklist.length;
    
    if (onComplete) {
      onComplete(completed, total);
    }
  }, [checklist, onComplete]);

  // Reset checklist at midnight
  useEffect(() => {
    const checkReset = () => {
      const lastReset = localStorage.getItem('checklist-last-reset');
      const today = new Date().toDateString();
      
      if (lastReset !== today) {
        setChecklist(DEFAULT_CHECKLIST);
        localStorage.setItem('checklist-last-reset', today);
      }
    };

    checkReset();
    const interval = setInterval(checkReset, 60000); // Check every minute
    
    return () => clearInterval(interval);
  }, []);

  const handleToggle = (id: string) => {
    setChecklist(prev =>
      prev.map(item =>
        item.id === id ? { ...item, completed: !item.completed } : item
      )
    );
  };

  const handleResetAll = () => {
    if (confirm('Reset all checklist items? This will mark all as incomplete.')) {
      setChecklist(DEFAULT_CHECKLIST);
    }
  };

  const getCategoryItems = (category: string) => {
    return checklist.filter(item => item.category === category);
  };

  const getCategoryProgress = (category: string) => {
    const items = getCategoryItems(category);
    const completed = items.filter(item => item.completed).length;
    return { completed, total: items.length, percentage: (completed / items.length) * 100 };
  };

  const categories = [
    { 
      id: 'pre-market', 
      label: 'Pre-Market', 
      icon: Calendar,
      color: 'text-blue-500',
      description: 'Before trading begins'
    },
    { 
      id: 'active-trading', 
      label: 'Active Trading', 
      icon: TrendingUp,
      color: 'text-green-500',
      description: 'During market hours'
    },
    { 
      id: 'post-market', 
      label: 'Post-Market', 
      icon: BarChart3,
      color: 'text-purple-500',
      description: 'After trading closes'
    },
  ];

  const totalProgress = getCategoryProgress('pre-market').completed +
                       getCategoryProgress('active-trading').completed +
                       getCategoryProgress('post-market').completed;
  const totalItems = checklist.length;
  const overallPercentage = (totalProgress / totalItems) * 100;

  const currentCategoryData = categories.find(c => c.id === activeCategory)!;
  const currentProgress = getCategoryProgress(activeCategory);
  const displayItems = getCategoryItems(activeCategory);
  const visibleItems = showCompleted ? displayItems : displayItems.filter(item => !item.completed);

  return (
    <div className="h-full flex flex-col">
      {/* Header with overall progress */}
      <div className="mb-6">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-3">
            <Clock className="w-6 h-6 text-gold-500" />
            <div>
              <h3 className="text-lg font-semibold">Daily Trading Checklist</h3>
              <p className="text-xs text-gray-400">
                {new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}
              </p>
            </div>
          </div>
          <button
            onClick={handleResetAll}
            className="text-xs text-gray-400 hover:text-white transition-colors"
          >
            Reset All
          </button>
        </div>

        {/* Overall progress bar */}
        <div className="mb-2">
          <div className="flex items-center justify-between text-sm mb-1">
            <span className="text-gray-400">Overall Progress</span>
            <span className="text-gold-500 font-semibold">
              {totalProgress}/{totalItems} ({overallPercentage.toFixed(0)}%)
            </span>
          </div>
          <div className="w-full bg-gray-700 rounded-full h-2">
            <div
              className="bg-gold-500 h-2 rounded-full transition-all duration-300"
              style={{ width: `${overallPercentage}%` }}
            />
          </div>
        </div>
      </div>

      {/* Category tabs */}
      <div className="flex gap-2 mb-4 border-b border-gray-700">
        {categories.map(category => {
          const progress = getCategoryProgress(category.id);
          const Icon = category.icon;
          
          return (
            <button
              key={category.id}
              onClick={() => setActiveCategory(category.id as any)}
              className={`flex-1 px-4 py-3 border-b-2 transition-colors ${
                activeCategory === category.id
                  ? 'border-gold-500 text-white'
                  : 'border-transparent text-gray-400 hover:text-white'
              }`}
            >
              <div className="flex items-center justify-center gap-2 mb-1">
                <Icon className={`w-4 h-4 ${activeCategory === category.id ? category.color : ''}`} />
                <span className="text-sm font-medium">{category.label}</span>
              </div>
              <div className="text-xs">
                {progress.completed}/{progress.total}
              </div>
            </button>
          );
        })}
      </div>

      {/* Category info */}
      <div className="mb-4 p-3 bg-dark-hover rounded-lg">
        <div className="flex items-center justify-between">
          <div>
            <h4 className={`font-semibold ${currentCategoryData.color}`}>
              {currentCategoryData.label}
            </h4>
            <p className="text-xs text-gray-400">{currentCategoryData.description}</p>
          </div>
          <div className="text-right">
            <div className="text-lg font-bold text-gold-500">
              {currentProgress.percentage.toFixed(0)}%
            </div>
            <div className="text-xs text-gray-400">
              {currentProgress.completed} / {currentProgress.total}
            </div>
          </div>
        </div>
      </div>

      {/* Show completed toggle */}
      <div className="mb-3 flex items-center justify-end">
        <label className="flex items-center gap-2 text-sm text-gray-400 cursor-pointer">
          <input
            type="checkbox"
            checked={showCompleted}
            onChange={(e) => setShowCompleted(e.target.checked)}
            className="rounded"
          />
          <span>Show completed</span>
        </label>
      </div>

      {/* Checklist items */}
      <div className="flex-1 overflow-y-auto space-y-2">
        {visibleItems.length === 0 ? (
          <div className="text-center py-8 text-gray-400">
            <CheckCircle2 className="w-12 h-12 mx-auto mb-3 text-green-500" />
            <p>All tasks completed!</p>
            <p className="text-sm">Great job on this section.</p>
          </div>
        ) : (
          visibleItems.map(item => (
            <button
              key={item.id}
              onClick={() => handleToggle(item.id)}
              className={`w-full p-4 rounded-lg border-2 transition-all text-left ${
                item.completed
                  ? 'border-green-500/30 bg-green-500/5'
                  : 'border-gray-700 hover:border-gray-600 bg-dark-hover'
              }`}
            >
              <div className="flex items-start gap-3">
                <div className="pt-0.5">
                  {item.completed ? (
                    <CheckCircle2 className="w-5 h-5 text-green-500" />
                  ) : (
                    <Circle className="w-5 h-5 text-gray-500" />
                  )}
                </div>
                <div className="flex-1">
                  <h5 className={`font-medium mb-1 ${
                    item.completed ? 'text-gray-500 line-through' : 'text-white'
                  }`}>
                    {item.title}
                  </h5>
                  <p className={`text-sm ${
                    item.completed ? 'text-gray-600' : 'text-gray-400'
                  }`}>
                    {item.description}
                  </p>
                </div>
              </div>
            </button>
          ))
        )}
      </div>

      {/* Category completion message */}
      {currentProgress.completed === currentProgress.total && currentProgress.total > 0 && (
        <div className="mt-4 p-3 bg-green-500/10 border border-green-500/30 rounded-lg">
          <div className="flex items-center gap-2 text-green-500">
            <AlertCircle className="w-5 h-5" />
            <span className="text-sm font-medium">
              {currentCategoryData.label} phase complete! 
              {activeCategory === 'pre-market' && ' Ready to trade.'}
              {activeCategory === 'active-trading' && ' Well managed!'}
              {activeCategory === 'post-market' && ' See you tomorrow!'}
            </span>
          </div>
        </div>
      )}
    </div>
  );
}
