import { useState, useEffect } from 'react';
import { Target, DollarSign, TrendingUp, TrendingDown, AlertTriangle, Save, Edit2, Sparkles } from 'lucide-react';
import { aiApi } from '../services/api';

interface TradingPlan {
  date: string;
  bias: 'BULLISH' | 'BEARISH' | 'NEUTRAL';
  dailyTarget: number;
  maxLoss: number;
  entryZone: { min: number; max: number };
  targetPrice: number;
  stopLoss: number;
  keyLevels: {
    support: number[];
    resistance: number[];
  };
  tradingNotes: string;
  maxTrades: number;
  actualTrades: number;
  actualPnL: number;
  planFollowed: boolean;
}

interface DailyTradingPlanProps {
  currentPrice: number;
  onPlanUpdate?: (plan: TradingPlan) => void;
}

export default function DailyTradingPlan({ currentPrice, onPlanUpdate }: DailyTradingPlanProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [generatingAI, setGeneratingAI] = useState(false);
  const [plan, setPlan] = useState<TradingPlan>(() => {
    const stored = localStorage.getItem('daily-trading-plan');
    const today = new Date().toDateString();
    
    if (stored) {
      try {
        const parsed = JSON.parse(stored);
        // If plan is from today, use it; otherwise create new
        if (parsed.date === today) {
          return parsed;
        }
      } catch {
        // Fall through to create new plan
      }
    }
    
    // Create new plan for today
    return {
      date: today,
      bias: 'NEUTRAL',
      dailyTarget: 500,
      maxLoss: 250,
      entryZone: { min: currentPrice - 10, max: currentPrice + 10 },
      targetPrice: currentPrice + 20,
      stopLoss: currentPrice - 15,
      keyLevels: {
        support: [currentPrice - 20, currentPrice - 40],
        resistance: [currentPrice + 20, currentPrice + 40],
      },
      tradingNotes: '',
      maxTrades: 3,
      actualTrades: 0,
      actualPnL: 0,
      planFollowed: true,
    };
  });

  useEffect(() => {
    localStorage.setItem('daily-trading-plan', JSON.stringify(plan));
    if (onPlanUpdate) {
      onPlanUpdate(plan);
    }
  }, [plan, onPlanUpdate]);

  const handleSave = () => {
    setIsEditing(false);
    // Trigger save notification could go here
  };

  const handleReset = () => {
    if (confirm('Create a new plan for today? This will clear current plan.')) {
      const today = new Date().toDateString();
      setPlan({
        date: today,
        bias: 'NEUTRAL',
        dailyTarget: 500,
        maxLoss: 250,
        entryZone: { min: currentPrice - 10, max: currentPrice + 10 },
        targetPrice: currentPrice + 20,
        stopLoss: currentPrice - 15,
        keyLevels: {
          support: [currentPrice - 20, currentPrice - 40],
          resistance: [currentPrice + 20, currentPrice + 40],
        },
        tradingNotes: '',
        maxTrades: 3,
        actualTrades: 0,
        actualPnL: 0,
        planFollowed: true,
      });
      setIsEditing(true);
    }
  };

  const handleGenerateWithAI = async () => {
    if (!confirm('Generate a trading plan using AI? This will use your indicator preferences.')) {
      return;
    }

    setGeneratingAI(true);
    try {
      const aiPlan = await aiApi.generateTradingPlan({
        current_price: currentPrice,
        risk_tolerance: 'moderate',
        use_indicator_preferences: true,
      });

      // Map AI response to our plan structure
      const today = new Date().toDateString();
      setPlan({
        date: today,
        bias: aiPlan.market_bias,
        dailyTarget: aiPlan.daily_target || 500,
        maxLoss: aiPlan.max_loss || 250,
        entryZone: {
          min: aiPlan.entry_zone_min || currentPrice - 10,
          max: aiPlan.entry_zone_max || currentPrice + 10,
        },
        targetPrice: aiPlan.target_price || currentPrice + 20,
        stopLoss: aiPlan.stop_loss || currentPrice - 15,
        keyLevels: {
          support: aiPlan.support_levels || [],
          resistance: aiPlan.resistance_levels || [],
        },
        tradingNotes: aiPlan.trading_notes || '',
        maxTrades: aiPlan.max_trades || 3,
        actualTrades: 0,
        actualPnL: 0,
        planFollowed: true,
      });

      setIsEditing(true);
      alert(`AI Plan Generated!\n\nBias: ${aiPlan.market_bias}\nConfidence: ${aiPlan.confidence}%\n\nYou can now review and edit the plan.`);
    } catch (error) {
      console.error('Failed to generate AI plan:', error);
      alert('Failed to generate AI plan. Please try again or create a manual plan.');
    } finally {
      setGeneratingAI(false);
    }
  };

  const addSupport = () => {
    setPlan(prev => ({
      ...prev,
      keyLevels: {
        ...prev.keyLevels,
        support: [...prev.keyLevels.support, currentPrice - 10],
      },
    }));
  };

  const addResistance = () => {
    setPlan(prev => ({
      ...prev,
      keyLevels: {
        ...prev.keyLevels,
        resistance: [...prev.keyLevels.resistance, currentPrice + 10],
      },
    }));
  };

  const removeSupport = (index: number) => {
    setPlan(prev => ({
      ...prev,
      keyLevels: {
        ...prev.keyLevels,
        support: prev.keyLevels.support.filter((_, i) => i !== index),
      },
    }));
  };

  const removeResistance = (index: number) => {
    setPlan(prev => ({
      ...prev,
      keyLevels: {
        ...prev.keyLevels,
        resistance: prev.keyLevels.resistance.filter((_, i) => i !== index),
      },
    }));
  };

  const updateSupport = (index: number, value: number) => {
    setPlan(prev => ({
      ...prev,
      keyLevels: {
        ...prev.keyLevels,
        support: prev.keyLevels.support.map((s, i) => i === index ? value : s),
      },
    }));
  };

  const updateResistance = (index: number, value: number) => {
    setPlan(prev => ({
      ...prev,
      keyLevels: {
        ...prev.keyLevels,
        resistance: prev.keyLevels.resistance.map((r, i) => i === index ? value : r),
      },
    }));
  };

  const targetReached = plan.actualPnL >= plan.dailyTarget;
  const maxLossReached = plan.actualPnL <= -plan.maxLoss;
  const shouldStopTrading = targetReached || maxLossReached;

  return (
    <div className="h-full flex flex-col overflow-y-auto">
      {/* Header */}
      <div className="mb-4 pb-4 border-b border-gray-700">
        <div className="flex items-center justify-between mb-2">
          <div className="flex items-center gap-3">
            <Target className="w-6 h-6 text-gold-500" />
            <div>
              <h3 className="text-lg font-semibold">Daily Trading Plan</h3>
              <p className="text-xs text-gray-400">
                {new Date(plan.date).toLocaleDateString('en-US', { 
                  weekday: 'long', 
                  month: 'long', 
                  day: 'numeric' 
                })}
              </p>
            </div>
          </div>
          <div className="flex gap-2">
            {!isEditing ? (
              <>
                <button
                  onClick={handleGenerateWithAI}
                  disabled={generatingAI}
                  className="btn-primary text-sm flex items-center gap-2 bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 disabled:from-gray-700 disabled:to-gray-700"
                >
                  <Sparkles className="w-4 h-4" />
                  {generatingAI ? 'Generating...' : 'AI Plan'}
                </button>
                <button
                  onClick={() => setIsEditing(true)}
                  className="btn-secondary text-sm flex items-center gap-2"
                >
                  <Edit2 className="w-4 h-4" />
                  Edit
                </button>
                <button
                  onClick={handleReset}
                  className="btn-secondary text-sm"
                >
                  New Plan
                </button>
              </>
            ) : (
              <button
                onClick={handleSave}
                className="btn-primary text-sm flex items-center gap-2"
              >
                <Save className="w-4 h-4" />
                Save
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Market Bias */}
      <div className="mb-4">
        <label className="block text-sm font-medium mb-2">Market Bias</label>
        <div className="grid grid-cols-3 gap-2">
          {(['BULLISH', 'NEUTRAL', 'BEARISH'] as const).map(bias => (
            <button
              key={bias}
              disabled={!isEditing}
              onClick={() => setPlan({ ...plan, bias })}
              className={`p-3 rounded-lg border-2 transition-all ${
                plan.bias === bias
                  ? bias === 'BULLISH'
                    ? 'border-green-500 bg-green-500/10 text-green-500'
                    : bias === 'BEARISH'
                    ? 'border-red-500 bg-red-500/10 text-red-500'
                    : 'border-gray-500 bg-gray-500/10 text-gray-300'
                  : 'border-gray-700 text-gray-400 hover:border-gray-600'
              } ${!isEditing ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'}`}
            >
              {bias === 'BULLISH' && <TrendingUp className="w-5 h-5 mx-auto mb-1" />}
              {bias === 'NEUTRAL' && <div className="w-5 h-0.5 bg-current mx-auto mb-2" />}
              {bias === 'BEARISH' && <TrendingDown className="w-5 h-5 mx-auto mb-1" />}
              <div className="text-xs font-medium">{bias}</div>
            </button>
          ))}
        </div>
      </div>

      {/* Risk Parameters */}
      <div className="grid grid-cols-2 gap-4 mb-4">
        <div>
          <label className="block text-sm font-medium mb-2">
            <DollarSign className="w-4 h-4 inline mr-1" />
            Daily Target
          </label>
          <input
            type="number"
            disabled={!isEditing}
            value={plan.dailyTarget}
            onChange={(e) => setPlan({ ...plan, dailyTarget: Number(e.target.value) })}
            className="w-full px-3 py-2 bg-dark-bg border border-gray-700 rounded-lg disabled:opacity-60"
            placeholder="500"
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-2">
            <AlertTriangle className="w-4 h-4 inline mr-1" />
            Max Loss
          </label>
          <input
            type="number"
            disabled={!isEditing}
            value={plan.maxLoss}
            onChange={(e) => setPlan({ ...plan, maxLoss: Number(e.target.value) })}
            className="w-full px-3 py-2 bg-dark-bg border border-gray-700 rounded-lg disabled:opacity-60"
            placeholder="250"
          />
        </div>
      </div>

      {/* Entry Zone */}
      <div className="mb-4">
        <label className="block text-sm font-medium mb-2">Entry Zone</label>
        <div className="grid grid-cols-2 gap-2">
          <div>
            <input
              type="number"
              disabled={!isEditing}
              step="0.01"
              value={plan.entryZone.min}
              onChange={(e) =>
                setPlan({
                  ...plan,
                  entryZone: { ...plan.entryZone, min: Number(e.target.value) },
                })
              }
              className="w-full px-3 py-2 bg-dark-bg border border-gray-700 rounded-lg text-sm disabled:opacity-60"
              placeholder="Min"
            />
            <p className="text-xs text-gray-500 mt-1">Minimum entry</p>
          </div>
          <div>
            <input
              type="number"
              disabled={!isEditing}
              step="0.01"
              value={plan.entryZone.max}
              onChange={(e) =>
                setPlan({
                  ...plan,
                  entryZone: { ...plan.entryZone, max: Number(e.target.value) },
                })
              }
              className="w-full px-3 py-2 bg-dark-bg border border-gray-700 rounded-lg text-sm disabled:opacity-60"
              placeholder="Max"
            />
            <p className="text-xs text-gray-500 mt-1">Maximum entry</p>
          </div>
        </div>
      </div>

      {/* Target & Stop Loss */}
      <div className="grid grid-cols-2 gap-4 mb-4">
        <div>
          <label className="block text-sm font-medium mb-2 text-green-500">Target Price</label>
          <input
            type="number"
            disabled={!isEditing}
            step="0.01"
            value={plan.targetPrice}
            onChange={(e) => setPlan({ ...plan, targetPrice: Number(e.target.value) })}
            className="w-full px-3 py-2 bg-dark-bg border border-green-500/30 rounded-lg disabled:opacity-60"
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-2 text-red-500">Stop Loss</label>
          <input
            type="number"
            disabled={!isEditing}
            step="0.01"
            value={plan.stopLoss}
            onChange={(e) => setPlan({ ...plan, stopLoss: Number(e.target.value) })}
            className="w-full px-3 py-2 bg-dark-bg border border-red-500/30 rounded-lg disabled:opacity-60"
          />
        </div>
      </div>

      {/* Key Levels */}
      <div className="mb-4">
        <label className="block text-sm font-medium mb-2">Support Levels</label>
        <div className="space-y-2 mb-2">
          {plan.keyLevels.support.map((level, index) => (
            <div key={index} className="flex gap-2">
              <input
                type="number"
                disabled={!isEditing}
                step="0.01"
                value={level}
                onChange={(e) => updateSupport(index, Number(e.target.value))}
                className="flex-1 px-3 py-2 bg-dark-bg border border-gray-700 rounded-lg text-sm disabled:opacity-60"
              />
              {isEditing && (
                <button
                  onClick={() => removeSupport(index)}
                  className="px-3 py-2 bg-red-500/20 text-red-500 rounded-lg hover:bg-red-500/30"
                >
                  ✕
                </button>
              )}
            </div>
          ))}
        </div>
        {isEditing && (
          <button onClick={addSupport} className="btn-secondary text-sm w-full">
            + Add Support
          </button>
        )}
      </div>

      <div className="mb-4">
        <label className="block text-sm font-medium mb-2">Resistance Levels</label>
        <div className="space-y-2 mb-2">
          {plan.keyLevels.resistance.map((level, index) => (
            <div key={index} className="flex gap-2">
              <input
                type="number"
                disabled={!isEditing}
                step="0.01"
                value={level}
                onChange={(e) => updateResistance(index, Number(e.target.value))}
                className="flex-1 px-3 py-2 bg-dark-bg border border-gray-700 rounded-lg text-sm disabled:opacity-60"
              />
              {isEditing && (
                <button
                  onClick={() => removeResistance(index)}
                  className="px-3 py-2 bg-red-500/20 text-red-500 rounded-lg hover:bg-red-500/30"
                >
                  ✕
                </button>
              )}
            </div>
          ))}
        </div>
        {isEditing && (
          <button onClick={addResistance} className="btn-secondary text-sm w-full">
            + Add Resistance
          </button>
        )}
      </div>

      {/* Max Trades */}
      <div className="mb-4">
        <label className="block text-sm font-medium mb-2">Maximum Trades Today</label>
        <input
          type="number"
          disabled={!isEditing}
          min={1}
          max={10}
          value={plan.maxTrades}
          onChange={(e) => setPlan({ ...plan, maxTrades: Number(e.target.value) })}
          className="w-full px-3 py-2 bg-dark-bg border border-gray-700 rounded-lg disabled:opacity-60"
        />
      </div>

      {/* Trading Notes */}
      <div className="mb-4">
        <label className="block text-sm font-medium mb-2">Trading Notes & Strategy</label>
        <textarea
          disabled={!isEditing}
          value={plan.tradingNotes}
          onChange={(e) => setPlan({ ...plan, tradingNotes: e.target.value })}
          className="w-full px-3 py-2 bg-dark-bg border border-gray-700 rounded-lg disabled:opacity-60"
          rows={4}
          placeholder="Market conditions, strategy notes, things to watch..."
        />
      </div>

      {/* Actual Performance (read-only summary) */}
      <div className="mt-auto pt-4 border-t border-gray-700">
        <h4 className="text-sm font-semibold mb-3">Today's Performance</h4>
        <div className="grid grid-cols-2 gap-3 mb-3">
          <div className="p-3 bg-dark-hover rounded-lg">
            <div className="text-xs text-gray-400 mb-1">Actual P&L</div>
            <div className={`text-lg font-bold ${
              plan.actualPnL > 0 ? 'text-green-500' : plan.actualPnL < 0 ? 'text-red-500' : 'text-gray-400'
            }`}>
              ${plan.actualPnL.toFixed(2)}
            </div>
          </div>
          <div className="p-3 bg-dark-hover rounded-lg">
            <div className="text-xs text-gray-400 mb-1">Trades Taken</div>
            <div className={`text-lg font-bold ${
              plan.actualTrades >= plan.maxTrades ? 'text-red-500' : 'text-white'
            }`}>
              {plan.actualTrades} / {plan.maxTrades}
            </div>
          </div>
        </div>

        {/* Trading Status Alert */}
        {shouldStopTrading && (
          <div className={`p-3 rounded-lg border-2 ${
            targetReached 
              ? 'bg-green-500/10 border-green-500/30 text-green-500'
              : 'bg-red-500/10 border-red-500/30 text-red-500'
          }`}>
            <div className="flex items-center gap-2 font-semibold">
              <AlertTriangle className="w-5 h-5" />
              {targetReached ? 'Daily Target Reached!' : 'Max Loss Hit!'}
            </div>
            <p className="text-sm mt-1">
              {targetReached 
                ? 'Consider stopping trading for today.' 
                : 'Stop trading immediately to preserve capital.'}
            </p>
          </div>
        )}

        {plan.actualTrades >= plan.maxTrades && !shouldStopTrading && (
          <div className="p-3 bg-yellow-500/10 border-2 border-yellow-500/30 rounded-lg text-yellow-500">
            <div className="flex items-center gap-2 font-semibold text-sm">
              <AlertTriangle className="w-4 h-4" />
              Maximum trades reached
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
