// ===== Greeks Overlay Tab =====
// Shows Delta, Gamma, Theta, Vega for ATM ±2 strikes
// Helps traders understand directional and time decay risks

function GreeksOverlayTab({ symbol = 'NIFTY' }) {
  const [atmData, setAtmData] = React.useState(null);
  const [selectedStrike, setSelectedStrike] = React.useState(null);
  const [selectedOptionType, setSelectedOptionType] = React.useState('CE');
  const [loading, setLoading] = React.useState(false);
  const toast = useToast();

  React.useEffect(() => {
    loadAtmData();
    const interval = setInterval(loadAtmData, 5000); // Refresh every 5 seconds
    return () => clearInterval(interval);
  }, [symbol]);

  const loadAtmData = async () => {
    setLoading(true);
    try {
      const response = await API.get(`/api/atm-strikes/${symbol}`);
      if (response.success && response.symbols?.length > 0) {
        const symbolData = response.symbols[0];
        setAtmData(symbolData);

        // Auto-select ATM strike if not already selected
        if (!selectedStrike && symbolData.strikes?.length > 0) {
          const atmStrike = symbolData.strikes.find(s => s.isAtm);
          if (atmStrike) {
            setSelectedStrike(atmStrike.strike);
          }
        }
      }
    } catch (error) {
      toast('Failed to load ATM data with Greeks', 'error');
    } finally {
      setLoading(false);
    }
  };

  const selectedData = selectedStrike && atmData?.strikes?.find(s => s.strike === selectedStrike);
  const selectedGreeks = selectedOptionType === 'CE' ? selectedData?.call?.greeks : selectedData?.put?.greeks;
  const selectedLevel = selectedOptionType === 'CE' ? selectedData?.call : selectedData?.put;

  return (
    <div className="p-4 space-y-4">
      {/* Header */}
      <div className="bg-white rounded-lg shadow p-4">
        <h2 className="text-xl font-bold mb-4">📊 Greeks Overlay - {symbol}</h2>

        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
          <div>
            <label className="block text-sm font-medium mb-1">Strike</label>
            <select
              value={selectedStrike || ''}
              onChange={(e) => setSelectedStrike(parseInt(e.target.value))}
              className="w-full px-3 py-2 border rounded"
            >
              <option value="">-- Select Strike --</option>
              {atmData?.strikes?.map(s => (
                <option key={s.strike} value={s.strike}>
                  {s.strike} {s.isAtm ? '(ATM)' : ''}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">Option Type</label>
            <select
              value={selectedOptionType}
              onChange={(e) => setSelectedOptionType(e.target.value)}
              className="w-full px-3 py-2 border rounded"
            >
              <option value="CE">Call (CE)</option>
              <option value="PE">Put (PE)</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">Spot Price</label>
            <div className="w-full px-3 py-2 border rounded bg-gray-100 flex items-center font-semibold">
              ₹{atmData?.spotPrice?.toFixed(2) || 'N/A'}
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">&nbsp;</label>
            <button
              onClick={loadAtmData}
              disabled={loading}
              className="w-full px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 font-medium"
            >
              {loading ? 'Updating...' : 'Refresh'}
            </button>
          </div>
        </div>
      </div>

      {/* Greeks Dashboard */}
      {selectedGreeks ? (
        <>
          {/* Greeks Cards */}
          <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
            <GreeksCard
              greekName="Delta (Δ)"
              value={selectedGreeks.delta}
              description="Directional exposure"
              color="bg-blue-50 border-blue-200"
              unit=""
              example={selectedOptionType === 'CE' ? '0.5 = 50% up move' : '-0.5 = 50% down move'}
            />
            <GreeksCard
              greekName="Gamma (Γ)"
              value={selectedGreeks.gamma}
              description="Delta acceleration"
              color="bg-purple-50 border-purple-200"
              unit=""
              example="Higher = more gamma scalp"
            />
            <GreeksCard
              greekName="Theta (Θ)"
              value={selectedGreeks.theta}
              description="Time decay/day"
              color="bg-orange-50 border-orange-200"
              unit=""
              example="Negative = you lose this daily"
            />
            <GreeksCard
              greekName="Vega (ν)"
              value={selectedGreeks.vega}
              description="Volatility (1%)"
              color="bg-green-50 border-green-200"
              unit=""
              example="0.1 = ₹0.10 if IV ↑ 1%"
            />
            <GreeksCard
              greekName="IV (σ)"
              value={selectedGreeks.iv}
              description="Implied Vol %"
              color="bg-red-50 border-red-200"
              unit="%"
              example="15% = market volatility"
            />
          </div>

          {/* Greeks Guide and Interpretation */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Greeks Interpretation */}
            <div className="bg-white rounded-lg shadow p-4">
              <h3 className="text-lg font-semibold mb-3">📖 Greeks Guide</h3>
              <GreeksExplanation optionType={selectedOptionType} greeks={selectedGreeks} />
            </div>

            {/* Trading Strategy Based on Greeks */}
            <div className="bg-white rounded-lg shadow p-4">
              <h3 className="text-lg font-semibold mb-3">📈 Trading Strategy Implications</h3>
              <StrategyRecommendation greeks={selectedGreeks} optionType={selectedOptionType} />
            </div>
          </div>

          {/* Greeks Comparison Table */}
          <div className="bg-white rounded-lg shadow p-4">
            <h3 className="text-lg font-semibold mb-3">📊 ATM ±2 Greeks Comparison</h3>
            <GreeksComparisonTable
              strikes={atmData?.strikes || []}
              optionType={selectedOptionType}
              selectedStrike={selectedStrike}
            />
          </div>
        </>
      ) : (
        <div className="bg-gray-50 rounded-lg p-8 text-center text-gray-600">
          <p className="text-lg">Select a strike to view Greeks</p>
          <p className="text-sm mt-2">Greeks show how option price will change with underlying movements</p>
        </div>
      )}

      {/* Educational Content */}
      <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
        <h3 className="font-semibold text-blue-900 mb-2">💡 Why Greeks Matter for Traders</h3>
        <ul className="text-sm text-blue-900 space-y-1">
          <li><strong>Delta:</strong> Want to bet on direction? Check Delta. Higher = more sensitive to spot moves.</li>
          <li><strong>Gamma:</strong> Want to scalp? Look for high Gamma strikes. They accelerate Delta faster.</li>
          <li><strong>Theta:</strong> Selling options? Theta is your profit source. Buying? It's your enemy.</li>
          <li><strong>Vega:</strong> Expect volatility to increase? Buy high-Vega strikes to profit from IV expansion.</li>
          <li><strong>IV:</strong> Higher IV = more expensive option. Compare IV across strikes to identify expensive ones.</li>
        </ul>
      </div>

      {/* Risk Warning */}
      <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 text-sm text-yellow-900">
        <strong>⚠️ Greeks Disclaimer:</strong>
        <p className="mt-2">
          Greeks are theoretical estimates and change continuously. This data refreshes every 5 seconds but may lag behind live market prices.
          Always cross-check with your broker's platform before executing trades.
        </p>
      </div>
    </div>
  );
}

/**
 * Greeks Card Component
 */
function GreeksCard({ greekName, value, description, color, unit, example }) {
  return (
    <div className={`border ${color} rounded p-3 text-center`}>
      <p className="text-xs font-medium text-gray-600 uppercase">{greekName}</p>
      <p className="text-2xl font-bold mt-1">
        {value !== null && value !== undefined ? `${value.toFixed(3)}${unit}` : 'N/A'}
      </p>
      <p className="text-xs text-gray-600 mt-1">{description}</p>
      <p className="text-xs text-gray-500 mt-1 italic">{example}</p>
    </div>
  );
}

/**
 * Greeks Explanation Component
 */
function GreeksExplanation({ optionType, greeks }) {
  return (
    <div className="space-y-3 text-sm">
      <div>
        <p className="font-semibold text-blue-900">Delta: {greeks?.delta?.toFixed(3) || 'N/A'}</p>
        <p className="text-gray-700 mt-1">
          {optionType === 'CE' ? 
            `For every ₹1 spot goes up, this CALL gains ₹${greeks?.delta?.toFixed(2) || 'N/A'}.` :
            `For every ₹1 spot goes down, this PUT gains ₹${Math.abs(greeks?.delta ?? 0).toFixed(2)}.`
          }
        </p>
      </div>

      <div>
        <p className="font-semibold text-purple-900">Gamma: {greeks?.gamma?.toFixed(4) || 'N/A'}</p>
        <p className="text-gray-700 mt-1">
          Delta accelerates at {greeks?.gamma?.toFixed(4) || 'N/A'} per ₹1 move. Higher gamma = faster Delta changes.
        </p>
      </div>

      <div>
        <p className="font-semibold text-orange-900">Theta: {greeks?.theta?.toFixed(4) || 'N/A'}</p>
        <p className="text-gray-700 mt-1">
          Time decay of ₹{Math.abs(greeks?.theta ?? 0).toFixed(2)}/day. {optionType === 'CE' ? 'You lose' : 'You gain'} this daily as expiry approaches.
        </p>
      </div>

      <div>
        <p className="font-semibold text-green-900">Vega: {greeks?.vega?.toFixed(4) || 'N/A'}</p>
        <p className="text-gray-700 mt-1">
          If implied volatility rises 1%, this option gains ₹{greeks?.vega?.toFixed(2) || 'N/A'}. Volatility bet included!
        </p>
      </div>
    </div>
  );
}

/**
 * Trading Strategy Recommendation
 */
function StrategyRecommendation({ greeks, optionType }) {
  const strategies = [];

  if (greeks?.delta && Math.abs(greeks.delta) > 0.7) {
    strategies.push('🎯 High Delta: This is very sensitive to spot moves — like owning the underlying');
  } else if (greeks?.delta && Math.abs(greeks.delta) < 0.3) {
    strategies.push('🎲 Low Delta: Cheap but less responsive to spot moves — risky bet');
  } else {
    strategies.push('⚖️ Medium Delta: Balanced risk/reward for directional bets');
  }

  if (greeks?.gamma && greeks.gamma > 0.01) {
    strategies.push('🔄 High Gamma: Great for scalping — Delta changes rapidly with spot moves');
  }

  if (greeks?.theta && greeks.theta < -0.05) {
    strategies.push('📉 High Negative Theta: Time decay works against you — don\'t hold long!');
  } else if (optionType === 'PE') {
    strategies.push('⏰ Watch Theta: It erodes this PUT daily');
  }

  if (greeks?.iv && greeks.iv > 30) {
    strategies.push('⚡ High IV: Expensive option — consider selling instead of buying');
  }

  return (
    <ul className="space-y-2 text-sm">
      {strategies.length > 0 ? (
        strategies.map((s, i) => <li key={i}>{s}</li>)
      ) : (
        <li>Balanced profile — adjust strategy based on your outlook</li>
      )}
    </ul>
  );
}

/**
 * Greeks Comparison Table across strikes
 */
function GreeksComparisonTable({ strikes, optionType, selectedStrike }) {
  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm border-collapse">
        <thead>
          <tr className="bg-gray-100 border-b">
            <th className="border px-3 py-2 text-left font-semibold">Strike</th>
            <th className="border px-3 py-2 text-right font-semibold">Delta</th>
            <th className="border px-3 py-2 text-right font-semibold">Gamma</th>
            <th className="border px-3 py-2 text-right font-semibold">Theta</th>
            <th className="border px-3 py-2 text-right font-semibold">Vega</th>
            <th className="border px-3 py-2 text-right font-semibold">IV %</th>
          </tr>
        </thead>
        <tbody>
          {strikes.map(s => {
            const level = optionType === 'CE' ? s.call : s.put;
            const greeks = level?.greeks;
            const isSelected = s.strike === selectedStrike;
            const isAtm = s.isAtm;

            return (
              <tr
                key={s.strike}
                className={`border-b ${isSelected ? 'bg-blue-100' : isAtm ? 'bg-yellow-50' : 'hover:bg-gray-50'}`}
              >
                <td className="border px-3 py-2 font-semibold">
                  {s.strike} {isAtm && '(ATM)'}
                </td>
                <td className="border px-3 py-2 text-right text-blue-600 font-medium">
                  {greeks?.delta?.toFixed(3) || '-'}
                </td>
                <td className="border px-3 py-2 text-right text-purple-600 font-medium">
                  {greeks?.gamma?.toFixed(4) || '-'}
                </td>
                <td className={`border px-3 py-2 text-right font-medium ${greeks?.theta ? (greeks.theta < 0 ? 'text-red-600' : 'text-green-600') : ''}`}>
                  {greeks?.theta?.toFixed(4) || '-'}
                </td>
                <td className="border px-3 py-2 text-right text-green-600 font-medium">
                  {greeks?.vega?.toFixed(4) || '-'}
                </td>
                <td className="border px-3 py-2 text-right text-orange-600 font-medium">
                  {greeks?.iv?.toFixed(1) || '-'}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}


