// ===== Smart Strike Selector Tab =====
// Recommends best strikes based on lot size
// Automatically selects strikes with best liquidity for the desired order size

function SmartStrikeSelectorTab({ symbol = 'NIFTY' }) {
  const [desiredLots, setDesiredLots] = React.useState(50);
  const [optionType, setOptionType] = React.useState('CE');
  const [recommendations, setRecommendations] = React.useState([]);
  const [spotPrice, setSpotPrice] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const toast = useToast();

  // Fetch recommendations when inputs change
  React.useEffect(() => {
    if (desiredLots >= 1) {
      fetchSmartStrikes();
    }
  }, [symbol, desiredLots, optionType]);

  const fetchSmartStrikes = async () => {
    setLoading(true);
    try {
      const response = await API.get(
        `/api/atm-strikes/${symbol}/smart-strikes/${desiredLots}/${optionType}`
      );

      if (response) {
        setSpotPrice(response.spotPrice);
        setRecommendations(response.recommendations || []);
      }
    } catch (error) {
      toast('Failed to fetch smart strike recommendations', 'error');
      setRecommendations([]);
    } finally {
      setLoading(false);
    }
  };

  const getLotSizeCategory = (lots) => {
    if (lots <= 10) return { name: 'Small Order', maxSpread: 0.50 };
    if (lots <= 25) return { name: 'Medium Order', maxSpread: 0.25 };
    if (lots <= 50) return { name: 'Large Order', maxSpread: 0.10 };
    return { name: 'Very Large Order', maxSpread: 0.05 };
  };

  const getLiquidityColor = (liquidityStatus) => {
    switch (liquidityStatus) {
      case 'VeryLiquid':
        return 'bg-green-50 border-l-4 border-green-500';
      case 'Acceptable':
        return 'bg-blue-50 border-l-4 border-blue-500';
      case 'Thin':
        return 'bg-yellow-50 border-l-4 border-yellow-500';
      case 'Dangerous':
        return 'bg-red-50 border-l-4 border-red-500';
      default:
        return 'bg-gray-50 border-l-4 border-gray-500';
    }
  };

  const getLiquidityBadge = (liquidityStatus) => {
    const badges = {
      VeryLiquid: 'bg-green-100 text-green-800',
      Acceptable: 'bg-blue-100 text-blue-800',
      Thin: 'bg-yellow-100 text-yellow-800',
      Dangerous: 'bg-red-100 text-red-800',
      NoQuote: 'bg-gray-100 text-gray-800'
    };
    return badges[liquidityStatus] || badges.NoQuote;
  };

  const category = getLotSizeCategory(desiredLots);

  return (
    <div className="p-4 space-y-4">
      {/* Header and Controls */}
      <div className="bg-white rounded-lg shadow p-4">
        <h2 className="text-xl font-bold mb-4">🎯 Smart Strike Selector - {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">
              Desired Lots
              <span className="text-xs text-gray-500 ml-1">({category.name})</span>
            </label>
            <input
              type="number"
              min="1"
              max="500"
              value={desiredLots}
              onChange={(e) => setDesiredLots(Math.max(1, parseInt(e.target.value) || 1))}
              className="w-full px-3 py-2 border rounded"
              placeholder="e.g., 50"
            />
            <p className="text-xs text-gray-600 mt-1">
              Max spread: <strong>₹{category.maxSpread.toFixed(2)}</strong>
            </p>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">Option Type</label>
            <select
              value={optionType}
              onChange={(e) => setOptionType(e.target.value)}
              className="w-full px-3 py-2 border rounded"
            >
              <option value="CE">Call (CE) - Bullish</option>
              <option value="PE">Put (PE) - Bearish</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">
              <span className="font-semibold text-lg">
                {spotPrice ? `₹${spotPrice.toFixed(2)}` : 'Loading...'}
              </span>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">&nbsp;</label>
            <button
              onClick={fetchSmartStrikes}
              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 ? 'Analyzing...' : 'Refresh'}
            </button>
          </div>
        </div>

        {/* Category Info */}
        <div className="bg-blue-50 border border-blue-200 rounded p-3 text-sm text-blue-900">
          <strong>📊 Order Size Analysis:</strong>
          <p className="mt-1">
            You're looking for a <strong>{category.name}</strong> with maximum acceptable spread of <strong>₹{category.maxSpread.toFixed(2)}</strong>.
            The selector will recommend the 3 best strikes within this limit.
          </p>
        </div>
      </div>

      {/* Recommendations */}
      <div className="space-y-3">
        <h3 className="text-lg font-semibold flex items-center gap-2">
          ⭐ Top Recommendations
          {recommendations.length > 0 && (
            <span className="text-sm font-normal text-gray-500">({recommendations.length} strikes)</span>
          )}
        </h3>

        {loading ? (
          <div className="text-center py-8 text-gray-500">Analyzing strikes...</div>
        ) : recommendations.length > 0 ? (
          recommendations.map((rec, idx) => (
            <RecommendationCard key={idx} recommendation={rec} rank={idx + 1} />
          ))
        ) : (
          <div className="bg-gray-50 rounded-lg p-6 text-center text-gray-600">
            <p>No recommendations available</p>
            <p className="text-xs mt-2">Try refreshing or check if market data is available</p>
          </div>
        )}
      </div>

      {/* Execution Strategy */}
      <div className="bg-white rounded-lg shadow p-4">
        <h3 className="text-lg font-semibold mb-3">📋 Execution Strategy</h3>
        <div className="space-y-2 text-sm">
          <p>
            <strong>1. Choose Your Strike:</strong> Select from the top 3 recommended strikes above
          </p>
          <p>
            <strong>2. Entry Point:</strong> Wait for liquidity to improve (Spread trending down)
          </p>
          <p>
            <strong>3. Order Placement:</strong> Split large orders into smaller chunks (10-25 lots each)
          </p>
          <p>
            <strong>4. Price Target:</strong> Use the "Estimated Execution Price" as reference
          </p>
          <p>
            <strong>5. Stop Loss:</strong> Keep slippage buffer = Estimated Slippage / Total Contracts
          </p>
        </div>
      </div>

      {/* Risk Warning */}
      <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-900">
        <strong>⚠️ Important Risks:</strong>
        <ul className="list-disc ml-6 mt-2">
          <li>"Dangerous" spreads (>= ₹2.00) can cause significant slippage on large orders</li>
          <li>Spread can widen rapidly during volatile markets</li>
          <li>This recommendation is based on current liquidity; actual execution may differ</li>
          <li>Always place orders during market hours and monitor execution closely</li>
        </ul>
      </div>
    </div>
  );
}

/**
 * Individual Recommendation Card
 */
function RecommendationCard({ recommendation, rank }) {
  const isATM = recommendation.recommendedStrike === recommendation.spotPrice; // Approximation
  const spreadPercentage = recommendation.spread ? ((recommendation.spread / (recommendation.bid || 1)) * 100).toFixed(1) : 'N/A';

  const getLiquidityColor = (liquidityStatus) => {
    switch (liquidityStatus) {
      case 'VeryLiquid':
        return 'bg-green-50 border-l-4 border-green-500';
      case 'Acceptable':
        return 'bg-blue-50 border-l-4 border-blue-500';
      case 'Thin':
        return 'bg-yellow-50 border-l-4 border-yellow-500';
      case 'Dangerous':
        return 'bg-red-50 border-l-4 border-red-500';
      default:
        return 'bg-gray-50 border-l-4 border-gray-500';
    }
  };

  const getBadgeClass = (liquidityStatus) => {
    const badges = {
      VeryLiquid: 'bg-green-100 text-green-800',
      Acceptable: 'bg-blue-100 text-blue-800',
      Thin: 'bg-yellow-100 text-yellow-800',
      Dangerous: 'bg-red-100 text-red-800',
      NoQuote: 'bg-gray-100 text-gray-800'
    };
    return badges[liquidityStatus] || badges.NoQuote;
  };

  return (
    <div className={`${getLiquidityColor(recommendation.liquidityStatus)} rounded-lg shadow p-4`}>
      {/* Header */}
      <div className="flex justify-between items-start mb-3">
        <div>
          <div className="flex items-center gap-2">
            <span className="text-2xl font-bold text-gray-700">#{rank}</span>
            <div>
              <p className="text-2xl font-bold">{recommendation.recommendedStrike}</p>
              <p className="text-xs text-gray-600">{recommendation.optionType} Strike</p>
            </div>
          </div>
        </div>
        <div className="text-right">
          <span className={`inline-block px-3 py-1 rounded-full text-sm font-semibold ${getBadgeClass(recommendation.liquidityStatus)}`}>
            {recommendation.liquidityStatus}
          </span>
          {isATM && (
            <p className="text-xs text-blue-600 font-semibold mt-1">ATM Strike</p>
          )}
        </div>
      </div>

      {/* Reason */}
      <p className="text-sm font-medium mb-3 text-gray-800">
        💭 {recommendation.reason}
      </p>

      {/* Pricing Grid */}
      <div className="grid grid-cols-3 gap-2 mb-3">
        <PriceCell label="Bid" value={`₹${recommendation.bid?.toFixed(2) || 'N/A'}`} />
        <PriceCell label="Spread" value={`₹${recommendation.spread?.toFixed(2) || 'N/A'}`} />
        <PriceCell label="Ask" value={`₹${recommendation.ask?.toFixed(2) || 'N/A'}`} />
      </div>

      {/* Impact Analysis */}
      <div className="bg-white bg-opacity-50 rounded p-3 space-y-2 text-sm">
        <div className="flex justify-between">
          <span className="font-medium">Estimated Execution Price:</span>
          <span className="font-bold text-lg">₹{recommendation.estimatedExecutionPrice?.toFixed(2) || 'N/A'}</span>
        </div>
        <div className="flex justify-between">
          <span className="font-medium">Total Slippage (Lots):</span>
          <span className="font-bold text-orange-600">₹{recommendation.estimatedSlippage?.toFixed(0) || 'N/A'}</span>
        </div>
        <div className="flex justify-between text-xs text-gray-700">
          <span>Spread % of Bid:</span>
          <span>{spreadPercentage}%</span>
        </div>
      </div>

      {/* Action Button */}
      <button className="w-full mt-3 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 font-medium text-sm">
        Select This Strike & Place Order
      </button>
    </div>
  );
}

/**
 * Simple Price Cell Component
 */
function PriceCell({ label, value }) {
  return (
    <div className="bg-white bg-opacity-60 rounded p-2 text-center">
      <p className="text-xs text-gray-600 font-medium">{label}</p>
      <p className="text-lg font-bold text-gray-800">{value}</p>
    </div>
  );
}


