/**
 * Scenario Simulation Page - PROFESSIONAL+ ONLY
 *
 * Interactive "what-if" analysis tool for strategic planning
 * Allows users to test different scenarios and see potential impacts on demand
 */

import React, { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useTenantStore } from '../../../../stores';
import { forecastingService } from '../../../../api/services/forecasting';
import {
  ScenarioType,
  ScenarioSimulationRequest,
  ScenarioSimulationResponse,
  WeatherScenario,
  CompetitionScenario,
  EventScenario,
  PricingScenario,
  PromotionScenario,
} from '../../../../api/types/forecasting';
import {
  Card,
  Button,
  Badge,
} from '../../../../components/ui';
import { AnalyticsPageLayout } from '../../../../components/analytics';
import {
  CloudRain,
  Sun,
  Users,
  Calendar,
  Tag,
  TrendingUp,
  AlertTriangle,
  CheckCircle,
  Lightbulb,
  BarChart3,
  ArrowUpRight,
  ArrowDownRight,
  Play,
  Sparkles,
  Package,
} from 'lucide-react';
import { useIngredients } from '../../../../api/hooks/inventory';
import { useModels } from '../../../../api/hooks/training';

export const ScenarioSimulationPage: React.FC = () => {
  const { t } = useTranslation();
  const currentTenant = useTenantStore((state) => state.currentTenant);

  const [selectedScenarioType, setSelectedScenarioType] = useState<ScenarioType>(ScenarioType.WEATHER);
  const [isSimulating, setIsSimulating] = useState(false);
  const [simulationResult, setSimulationResult] = useState<ScenarioSimulationResponse | null>(null);
  const [error, setError] = useState<string | null>(null);

  // Form state
  const [scenarioName, setScenarioName] = useState('');
  const [startDate, setStartDate] = useState(new Date().toISOString().split('T')[0]);
  const [durationDays, setDurationDays] = useState(7);
  const [selectedProducts, setSelectedProducts] = useState<string[]>([]);

  // Fetch real inventory data
  const {
    data: ingredientsData,
    isLoading: ingredientsLoading,
  } = useIngredients(currentTenant?.id || '');

  // Fetch trained models to filter products
  const {
    data: modelsData,
    isLoading: modelsLoading,
  } = useModels(currentTenant?.id || '', { active_only: true });

  // Build products list from ingredients that have trained models
  const availableProducts = useMemo(() => {
    if (!ingredientsData || !modelsData) {
      return [];
    }

    // Handle both array and paginated response formats
    const modelsList = Array.isArray(modelsData) ? modelsData : (modelsData.models || modelsData.items || []);

    // Get inventory product IDs that have trained models
    const modelProductIds = new Set(modelsList.map((model: any) => model.inventory_product_id));

    // Filter ingredients to only those with models
    const ingredientsWithModels = ingredientsData.filter(ingredient =>
      modelProductIds.has(ingredient.id)
    );

    return ingredientsWithModels.map(ingredient => ({
      id: ingredient.id,
      name: ingredient.name,
      category: ingredient.category || 'Other',
      hasModel: true
    }));
  }, [ingredientsData, modelsData]);

  // Scenario-specific parameters
  const [weatherParams, setWeatherParams] = useState<WeatherScenario>({
    temperature_change: 15,
    weather_type: 'heatwave',
  });
  const [competitionParams, setCompetitionParams] = useState<CompetitionScenario>({
    new_competitors: 1,
    distance_km: 0.5,
    estimated_market_share_loss: 0.15,
  });
  const [eventParams, setEventParams] = useState<EventScenario>({
    event_type: 'festival',
    expected_attendance: 5000,
    distance_km: 1.0,
    duration_days: 3,
  });
  const [pricingParams, setPricingParams] = useState<PricingScenario>({
    price_change_percent: 10,
  });
  const [promotionParams, setPromotionParams] = useState<PromotionScenario>({
    discount_percent: 20,
    promotion_type: 'discount',
    expected_traffic_increase: 0.3,
  });
  const [holidayParams, setHolidayParams] = useState({
    holiday_name: 'christmas',
    expected_impact_multiplier: 1.5,
  });
  const [supplyDisruptionParams, setSupplyDisruptionParams] = useState({
    severity: 'moderate',
    affected_percentage: 30,
    duration_days: 7,
  });
  const [customParams, setCustomParams] = useState<Record<string, number>>({});

  const handleSimulate = async () => {
    if (!currentTenant?.id) return;
    if (!scenarioName || selectedProducts.length === 0) {
      setError('Please provide a scenario name and select at least one product');
      return;
    }

    setIsSimulating(true);
    setError(null);

    try {
      const request: ScenarioSimulationRequest = {
        scenario_name: scenarioName,
        scenario_type: selectedScenarioType,
        inventory_product_ids: selectedProducts,
        start_date: startDate,
        duration_days: durationDays,
        include_baseline: true,
      };

      // Add scenario-specific parameters
      switch (selectedScenarioType) {
        case ScenarioType.WEATHER:
          request.weather_params = weatherParams;
          break;
        case ScenarioType.COMPETITION:
          request.competition_params = competitionParams;
          break;
        case ScenarioType.EVENT:
          request.event_params = eventParams;
          break;
        case ScenarioType.PRICING:
          request.pricing_params = pricingParams;
          break;
        case ScenarioType.PROMOTION:
          request.promotion_params = promotionParams;
          break;
        case ScenarioType.HOLIDAY:
          request.custom_multipliers = { holiday_multiplier: holidayParams.expected_impact_multiplier };
          break;
        case ScenarioType.SUPPLY_DISRUPTION:
          request.custom_multipliers = { disruption_severity: supplyDisruptionParams.affected_percentage / 100 };
          break;
        case ScenarioType.CUSTOM:
          request.custom_multipliers = customParams;
          break;
      }

      const result = await forecastingService.simulateScenario(currentTenant.id, request);
      setSimulationResult(result);
    } catch (err: any) {
      console.error('Simulation error:', err);

      if (err.response?.status === 402) {
        setError('This feature requires a Professional or Enterprise subscription. Please upgrade your plan to access scenario simulation tools.');
      } else {
        setError(err.response?.data?.detail || 'Failed to run scenario simulation');
      }
    } finally {
      setIsSimulating(false);
    }
  };

  const scenarioIcons = {
    [ScenarioType.WEATHER]: CloudRain,
    [ScenarioType.COMPETITION]: Users,
    [ScenarioType.EVENT]: Calendar,
    [ScenarioType.PRICING]: Tag,
    [ScenarioType.PROMOTION]: TrendingUp,
    [ScenarioType.HOLIDAY]: Calendar,
    [ScenarioType.SUPPLY_DISRUPTION]: AlertTriangle,
    [ScenarioType.CUSTOM]: Sparkles,
  };

  const getRiskLevelColor = (riskLevel: string) => {
    switch (riskLevel) {
      case 'high':
        return 'error';
      case 'medium':
        return 'warning';
      case 'low':
        return 'success';
      default:
        return 'default';
    }
  };

  return (
    <AnalyticsPageLayout
      title={t('analytics.scenario_simulation.title', 'Scenario Simulation')}
      description={t('analytics.scenario_simulation.subtitle', 'Test "what-if" scenarios to optimize your planning')}
      subscriptionLoading={false}
      hasAccess={true}
      dataLoading={isSimulating}
      showMobileNotice={true}
    >
      {error && (
        <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
          <AlertTriangle className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
          <div className="flex-1">
            <p className="text-sm text-red-800">{error}</p>
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Left Column: Configuration */}
        <div className="space-y-6">
          <Card>
            <div className="p-6 space-y-6">
              <div>
                <h3 className="text-lg font-semibold mb-4">
                  {t('analytics.scenario_simulation.configure', 'Configure Scenario')}
                </h3>

                {/* Scenario Name */}
                <div className="space-y-2">
                  <label className="text-sm font-medium">
                    {t('analytics.scenario_simulation.scenario_name', 'Scenario Name')}
                  </label>
                  <input
                    type="text"
                    value={scenarioName}
                    onChange={(e) => setScenarioName(e.target.value)}
                    placeholder={t('analytics.scenario_simulation.scenario_name_placeholder', 'e.g., Summer Heatwave Impact')}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>

                {/* Date Range */}
                <div className="grid grid-cols-2 gap-4 mt-4">
                  <div className="space-y-2">
                    <label className="text-sm font-medium">
                      {t('analytics.scenario_simulation.start_date', 'Start Date')}
                    </label>
                    <input
                      type="date"
                      value={startDate}
                      onChange={(e) => setStartDate(e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      min={new Date().toISOString().split('T')[0]}
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium">
                      {t('analytics.scenario_simulation.duration', 'Duration (days)')}
                    </label>
                    <input
                      type="number"
                      value={durationDays}
                      onChange={(e) => setDurationDays(parseInt(e.target.value) || 7)}
                      min={1}
                      max={30}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    />
                  </div>
                </div>

                {/* Product Selection */}
                <div className="mt-4 space-y-3">
                  <div className="flex items-center justify-between">
                    <label className="text-sm font-medium flex items-center gap-2">
                      <Package className="w-4 h-4" />
                      {t('analytics.scenario_simulation.select_products', 'Select Products to Simulate')}
                    </label>
                    <span className="text-xs text-gray-500">
                      {selectedProducts.length} selected
                    </span>
                  </div>

                  {ingredientsLoading || modelsLoading ? (
                    <div className="p-4 border rounded-lg text-center text-sm text-gray-500">
                      Loading products...
                    </div>
                  ) : availableProducts.length === 0 ? (
                    <div className="p-4 border border-amber-200 bg-amber-50 rounded-lg">
                      <div className="flex items-start gap-2">
                        <AlertTriangle className="w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5" />
                        <div className="text-sm text-amber-800">
                          <p className="font-medium">No products available for simulation</p>
                          <p className="mt-1">You need to train ML models for your products first. Visit the Training section to get started.</p>
                        </div>
                      </div>
                    </div>
                  ) : (
                    <>
                      {/* Quick Select All/None */}
                      <div className="flex gap-2">
                        <button
                          onClick={() => setSelectedProducts(availableProducts.map(p => p.id))}
                          className="text-xs text-blue-600 hover:text-blue-700 font-medium"
                        >
                          Select All
                        </button>
                        <span className="text-xs text-gray-300">|</span>
                        <button
                          onClick={() => setSelectedProducts([])}
                          className="text-xs text-gray-600 hover:text-gray-700 font-medium"
                        >
                          Clear All
                        </button>
                      </div>

                      {/* Product Grid */}
                      <div className="max-h-64 overflow-y-auto border border-gray-300 dark:border-gray-600 rounded-lg p-3 space-y-2 bg-gray-50 dark:bg-gray-800">
                        {availableProducts.map((product) => (
                          <label
                            key={product.id}
                            className={`flex items-center gap-3 p-3 border rounded-lg cursor-pointer transition-all ${
                              selectedProducts.includes(product.id)
                                ? 'border-blue-500 dark:border-blue-400 bg-blue-50 dark:bg-blue-900/30'
                                : 'border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-700 hover:border-gray-300 dark:hover:border-gray-500'
                            }`}
                          >
                            <input
                              type="checkbox"
                              checked={selectedProducts.includes(product.id)}
                              onChange={(e) => {
                                if (e.target.checked) {
                                  setSelectedProducts([...selectedProducts, product.id]);
                                } else {
                                  setSelectedProducts(selectedProducts.filter(id => id !== product.id));
                                }
                              }}
                              className="w-4 h-4 text-blue-600 border-gray-300 dark:border-gray-500 rounded focus:ring-blue-500 dark:bg-gray-600"
                            />
                            <div className="flex-1">
                              <div className="text-sm font-medium text-gray-900 dark:text-gray-100">{product.name}</div>
                              <div className="text-xs text-gray-500 dark:text-gray-400">{product.category}</div>
                            </div>
                            <Badge variant="success" className="text-xs">
                              ML Ready
                            </Badge>
                          </label>
                        ))}
                      </div>
                    </>
                  )}
                </div>
              </div>

              <div>
                <h4 className="text-sm font-medium mb-3">
                  {t('analytics.scenario_simulation.scenario_type', 'Scenario Type')}
                </h4>
                <div className="grid grid-cols-2 gap-3">
                  {Object.values(ScenarioType).map((type) => {
                    const Icon = scenarioIcons[type];
                    return (
                      <button
                        key={type}
                        onClick={() => setSelectedScenarioType(type)}
                        className={`p-3 border rounded-lg flex items-center gap-2 transition-all ${
                          selectedScenarioType === type
                            ? 'border-blue-500 bg-blue-50'
                            : 'border-gray-200 hover:border-gray-300'
                        }`}
                      >
                        <Icon className="w-4 h-4" />
                        <span className="text-sm capitalize">{type.replace('_', ' ')}</span>
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Scenario-Specific Parameters */}
              <div className="pt-4 border-t">
                <h4 className="text-sm font-medium mb-3">
                  {t('analytics.scenario_simulation.parameters', 'Parameters')}
                </h4>

                {selectedScenarioType === ScenarioType.WEATHER && (
                  <div className="space-y-3">
                    <div>
                      <label className="text-sm">Temperature Change (°C)</label>
                      <input
                        type="number"
                        value={weatherParams.temperature_change || 0}
                        onChange={(e) => setWeatherParams({ ...weatherParams, temperature_change: parseFloat(e.target.value) })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        min={-30}
                        max={30}
                      />
                    </div>
                    <div>
                      <label className="text-sm">Weather Type</label>
                      <select
                        value={weatherParams.weather_type || 'heatwave'}
                        onChange={(e) => setWeatherParams({ ...weatherParams, weather_type: e.target.value })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value="heatwave">Heatwave</option>
                        <option value="cold_snap">Cold Snap</option>
                        <option value="rainy">Rainy</option>
                        <option value="stormy">Stormy</option>
                      </select>
                    </div>
                  </div>
                )}

                {selectedScenarioType === ScenarioType.COMPETITION && (
                  <div className="space-y-3">
                    <div>
                      <label className="text-sm">New Competitors</label>
                      <input
                        type="number"
                        value={competitionParams.new_competitors}
                        onChange={(e) => setCompetitionParams({ ...competitionParams, new_competitors: parseInt(e.target.value) || 1 })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        min={1}
                        max={10}
                      />
                    </div>
                    <div>
                      <label className="text-sm">Distance (km)</label>
                      <input
                        type="number"
                        step="0.1"
                        value={competitionParams.distance_km}
                        onChange={(e) => setCompetitionParams({ ...competitionParams, distance_km: parseFloat(e.target.value) })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        min={0.1}
                        max={10}
                      />
                    </div>
                    <div>
                      <label className="text-sm">Est. Market Share Loss (%)</label>
                      <input
                        type="number"
                        value={competitionParams.estimated_market_share_loss * 100}
                        onChange={(e) => setCompetitionParams({ ...competitionParams, estimated_market_share_loss: parseFloat(e.target.value) / 100 })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        min={0}
                        max={50}
                      />
                    </div>
                  </div>
                )}

                {selectedScenarioType === ScenarioType.PROMOTION && (
                  <div className="space-y-3">
                    <div>
                      <label className="text-sm">Discount (%)</label>
                      <input
                        type="number"
                        value={promotionParams.discount_percent}
                        onChange={(e) => setPromotionParams({ ...promotionParams, discount_percent: parseFloat(e.target.value) })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        min={0}
                        max={75}
                      />
                      <p className="text-xs text-gray-500 mt-1">Typical range: 10-30%</p>
                    </div>
                    <div>
                      <label className="text-sm">Promotion Type</label>
                      <select
                        value={promotionParams.promotion_type}
                        onChange={(e) => setPromotionParams({ ...promotionParams, promotion_type: e.target.value })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value="discount">Discount</option>
                        <option value="bogo">Buy One Get One</option>
                        <option value="bundle">Bundle Deal</option>
                        <option value="flash_sale">Flash Sale</option>
                      </select>
                    </div>
                    <div>
                      <label className="text-sm">Expected Traffic Increase (%)</label>
                      <input
                        type="number"
                        value={promotionParams.expected_traffic_increase * 100}
                        onChange={(e) => setPromotionParams({ ...promotionParams, expected_traffic_increase: parseFloat(e.target.value) / 100 })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        min={0}
                        max={200}
                      />
                      <p className="text-xs text-gray-500 mt-1">Most promotions see 20-50% increase</p>
                    </div>
                  </div>
                )}

                {selectedScenarioType === ScenarioType.EVENT && (
                  <div className="space-y-3">
                    <div>
                      <label className="text-sm">Event Type</label>
                      <select
                        value={eventParams.event_type}
                        onChange={(e) => setEventParams({ ...eventParams, event_type: e.target.value })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value="festival">Festival</option>
                        <option value="sports">Sports Event</option>
                        <option value="concert">Concert</option>
                        <option value="conference">Conference</option>
                        <option value="market">Street Market</option>
                      </select>
                    </div>
                    <div>
                      <label className="text-sm">Expected Attendance</label>
                      <input
                        type="number"
                        value={eventParams.expected_attendance}
                        onChange={(e) => setEventParams({ ...eventParams, expected_attendance: parseInt(e.target.value) || 0 })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        min={100}
                        step={100}
                      />
                      <p className="text-xs text-gray-500 mt-1">Number of people expected</p>
                    </div>
                    <div>
                      <label className="text-sm">Distance from Location (km)</label>
                      <input
                        type="number"
                        step="0.1"
                        value={eventParams.distance_km}
                        onChange={(e) => setEventParams({ ...eventParams, distance_km: parseFloat(e.target.value) })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        min={0}
                        max={50}
                      />
                      <p className="text-xs text-gray-500 mt-1">Closer events have bigger impact</p>
                    </div>
                    <div>
                      <label className="text-sm">Event Duration (days)</label>
                      <input
                        type="number"
                        value={eventParams.duration_days}
                        onChange={(e) => setEventParams({ ...eventParams, duration_days: parseInt(e.target.value) || 1 })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        min={1}
                        max={30}
                      />
                    </div>
                  </div>
                )}

                {selectedScenarioType === ScenarioType.PRICING && (
                  <div className="space-y-3">
                    <div>
                      <label className="text-sm">Price Change (%)</label>
                      <input
                        type="number"
                        value={pricingParams.price_change_percent}
                        onChange={(e) => setPricingParams({ ...pricingParams, price_change_percent: parseFloat(e.target.value) })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        min={-50}
                        max={100}
                      />
                      <p className="text-xs text-gray-500 mt-1">
                        Negative for price decrease, positive for increase
                      </p>
                    </div>
                    <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                      <div className="text-xs text-blue-800">
                        <p className="font-medium">💡 Pricing Impact Guide:</p>
                        <ul className="mt-1 space-y-1 ml-4 list-disc">
                          <li>-10% price: Usually +8-12% demand</li>
                          <li>+10% price: Usually -8-12% demand</li>
                          <li>Impact varies by product type and competition</li>
                        </ul>
                      </div>
                    </div>
                  </div>
                )}

                {selectedScenarioType === ScenarioType.HOLIDAY && (
                  <div className="space-y-3">
                    <div>
                      <label className="text-sm">Holiday Period</label>
                      <select
                        value={holidayParams.holiday_name}
                        onChange={(e) => setHolidayParams({ ...holidayParams, holiday_name: e.target.value })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value="christmas">Christmas</option>
                        <option value="new_year">New Year</option>
                        <option value="easter">Easter</option>
                        <option value="valentines">Valentine's Day</option>
                        <option value="mothers_day">Mother's Day</option>
                        <option value="thanksgiving">Thanksgiving</option>
                        <option value="halloween">Halloween</option>
                      </select>
                    </div>
                    <div>
                      <label className="text-sm">Expected Impact Multiplier</label>
                      <input
                        type="number"
                        step="0.1"
                        value={holidayParams.expected_impact_multiplier}
                        onChange={(e) => setHolidayParams({ ...holidayParams, expected_impact_multiplier: parseFloat(e.target.value) })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        min={0.5}
                        max={3}
                      />
                      <p className="text-xs text-gray-500 mt-1">
                        1.0 = no change, 1.5 = 50% increase, 0.8 = 20% decrease
                      </p>
                    </div>
                  </div>
                )}

                {selectedScenarioType === ScenarioType.SUPPLY_DISRUPTION && (
                  <div className="space-y-3">
                    <div>
                      <label className="text-sm">Disruption Severity</label>
                      <select
                        value={supplyDisruptionParams.severity}
                        onChange={(e) => setSupplyDisruptionParams({ ...supplyDisruptionParams, severity: e.target.value })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value="minor">Minor (10-20% affected)</option>
                        <option value="moderate">Moderate (20-40% affected)</option>
                        <option value="major">Major (40-60% affected)</option>
                        <option value="severe">Severe (60%+ affected)</option>
                      </select>
                    </div>
                    <div>
                      <label className="text-sm">Affected Supply (%)</label>
                      <input
                        type="number"
                        value={supplyDisruptionParams.affected_percentage}
                        onChange={(e) => setSupplyDisruptionParams({ ...supplyDisruptionParams, affected_percentage: parseInt(e.target.value) || 0 })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        min={0}
                        max={100}
                      />
                      <p className="text-xs text-gray-500 mt-1">
                        Percentage of normal supply that will be unavailable
                      </p>
                    </div>
                    <div>
                      <label className="text-sm">Expected Duration (days)</label>
                      <input
                        type="number"
                        value={supplyDisruptionParams.duration_days}
                        onChange={(e) => setSupplyDisruptionParams({ ...supplyDisruptionParams, duration_days: parseInt(e.target.value) || 1 })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        min={1}
                        max={30}
                      />
                    </div>
                  </div>
                )}

                {selectedScenarioType === ScenarioType.CUSTOM && (
                  <div className="space-y-3">
                    <div className="p-3 bg-purple-50 border border-purple-200 rounded-lg">
                      <p className="text-sm text-purple-800 font-medium">Custom Scenario</p>
                      <p className="text-xs text-purple-700 mt-1">
                        Define your own demand multiplier for unique situations
                      </p>
                    </div>
                    <div>
                      <label className="text-sm">Demand Multiplier</label>
                      <input
                        type="number"
                        step="0.1"
                        value={customParams.custom_multiplier || 1.0}
                        onChange={(e) => setCustomParams({ custom_multiplier: parseFloat(e.target.value) })}
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        min={0}
                        max={5}
                      />
                      <p className="text-xs text-gray-500 mt-1">
                        1.0 = no change, 1.5 = 50% increase, 0.7 = 30% decrease
                      </p>
                    </div>
                    <div>
                      <label className="text-sm">Scenario Description (optional)</label>
                      <textarea
                        placeholder="Describe what you're simulating..."
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg mt-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        rows={3}
                      />
                    </div>
                  </div>
                )}
              </div>

              <Button
                onClick={handleSimulate}
                disabled={isSimulating || !scenarioName}
                className="w-full"
                size="lg"
              >
                <Play className="w-4 h-4 mr-2" />
                {isSimulating ? t('common.simulating', 'Simulating...') : t('common.run_simulation', 'Run Simulation')}
              </Button>
            </div>
          </Card>

          {/* Quick Examples */}
          <Card>
            <div className="p-6">
              <h3 className="text-sm font-semibold mb-4 flex items-center gap-2">
                <Lightbulb className="w-5 h-5 text-yellow-500" />
                {t('analytics.scenario_simulation.quick_examples', 'Quick Start Templates')}
              </h3>
              <p className="text-xs text-gray-600 mb-4">
                Click any template to pre-fill the scenario parameters
              </p>
              <div className="space-y-2">
                <button
                  onClick={() => {
                    setSelectedScenarioType(ScenarioType.WEATHER);
                    setScenarioName('Summer Heatwave Impact');
                    setWeatherParams({ temperature_change: 15, weather_type: 'heatwave' });
                    setDurationDays(7);
                  }}
                  className="w-full text-left px-4 py-3 border-2 border-orange-200 bg-orange-50 rounded-lg hover:bg-orange-100 hover:border-orange-300 transition-all group"
                >
                  <div className="flex items-start gap-3">
                    <Sun className="w-5 h-5 text-orange-600 mt-0.5" />
                    <div className="flex-1">
                      <div className="text-sm font-medium text-gray-900">Summer Heatwave</div>
                      <div className="text-xs text-gray-600 mt-1">
                        +15°C temperature spike - See impact on cold drinks & ice cream
                      </div>
                    </div>
                    <Badge variant="warning" className="text-xs">+20-40%</Badge>
                  </div>
                </button>

                <button
                  onClick={() => {
                    setSelectedScenarioType(ScenarioType.COMPETITION);
                    setScenarioName('New Competitor Opening');
                    setCompetitionParams({ new_competitors: 1, distance_km: 0.3, estimated_market_share_loss: 0.2 });
                    setDurationDays(30);
                  }}
                  className="w-full text-left px-4 py-3 border-2 border-red-200 bg-red-50 rounded-lg hover:bg-red-100 hover:border-red-300 transition-all"
                >
                  <div className="flex items-start gap-3">
                    <Users className="w-5 h-5 text-red-600 mt-0.5" />
                    <div className="flex-1">
                      <div className="text-sm font-medium text-gray-900">New Nearby Competitor</div>
                      <div className="text-xs text-gray-600 mt-1">
                        Bakery opening 300m away - Est. 20% market share loss
                      </div>
                    </div>
                    <Badge variant="error" className="text-xs">-15-25%</Badge>
                  </div>
                </button>

                <button
                  onClick={() => {
                    setSelectedScenarioType(ScenarioType.PROMOTION);
                    setScenarioName('Weekend Flash Sale');
                    setPromotionParams({ discount_percent: 25, promotion_type: 'flash_sale', expected_traffic_increase: 0.5 });
                    setDurationDays(3);
                  }}
                  className="w-full text-left px-4 py-3 border-2 border-green-200 bg-green-50 rounded-lg hover:bg-green-100 hover:border-green-300 transition-all"
                >
                  <div className="flex items-start gap-3">
                    <Tag className="w-5 h-5 text-green-600 mt-0.5" />
                    <div className="flex-1">
                      <div className="text-sm font-medium text-gray-900">Weekend Flash Sale</div>
                      <div className="text-xs text-gray-600 mt-1">
                        25% discount + 50% traffic boost - Test promotion impact
                      </div>
                    </div>
                    <Badge variant="success" className="text-xs">+40-60%</Badge>
                  </div>
                </button>

                <button
                  onClick={() => {
                    setSelectedScenarioType(ScenarioType.EVENT);
                    setScenarioName('Local Festival Impact');
                    setEventParams({ event_type: 'festival', expected_attendance: 5000, distance_km: 0.5, duration_days: 3 });
                    setDurationDays(3);
                  }}
                  className="w-full text-left px-4 py-3 border-2 border-purple-200 bg-purple-50 rounded-lg hover:bg-purple-100 hover:border-purple-300 transition-all"
                >
                  <div className="flex items-start gap-3">
                    <Calendar className="w-5 h-5 text-purple-600 mt-0.5" />
                    <div className="flex-1">
                      <div className="text-sm font-medium text-gray-900">Local Festival</div>
                      <div className="text-xs text-gray-600 mt-1">
                        5,000 attendees 500m away - Capture festival traffic
                      </div>
                    </div>
                    <Badge variant="primary" className="text-xs">+30-50%</Badge>
                  </div>
                </button>

                <button
                  onClick={() => {
                    setSelectedScenarioType(ScenarioType.HOLIDAY);
                    setScenarioName('Christmas Holiday Rush');
                    setHolidayParams({ holiday_name: 'christmas', expected_impact_multiplier: 1.8 });
                    setDurationDays(14);
                  }}
                  className="w-full text-left px-4 py-3 border-2 border-blue-200 bg-blue-50 rounded-lg hover:bg-blue-100 hover:border-blue-300 transition-all"
                >
                  <div className="flex items-start gap-3">
                    <Sparkles className="w-5 h-5 text-blue-600 mt-0.5" />
                    <div className="flex-1">
                      <div className="text-sm font-medium text-gray-900">Christmas Season</div>
                      <div className="text-xs text-gray-600 mt-1">
                        Holiday demand spike - Plan for seasonal products
                      </div>
                    </div>
                    <Badge variant="primary" className="text-xs">+60-100%</Badge>
                  </div>
                </button>

                <button
                  onClick={() => {
                    setSelectedScenarioType(ScenarioType.PRICING);
                    setScenarioName('Price Adjustment Test');
                    setPricingParams({ price_change_percent: -10 });
                    setDurationDays(14);
                  }}
                  className="w-full text-left px-4 py-3 border-2 border-indigo-200 bg-indigo-50 rounded-lg hover:bg-indigo-100 hover:border-indigo-300 transition-all"
                >
                  <div className="flex items-start gap-3">
                    <TrendingUp className="w-5 h-5 text-indigo-600 mt-0.5" />
                    <div className="flex-1">
                      <div className="text-sm font-medium text-gray-900">Price Decrease</div>
                      <div className="text-xs text-gray-600 mt-1">
                        10% price reduction - Test elasticity and demand response
                      </div>
                    </div>
                    <Badge variant="info" className="text-xs">+8-15%</Badge>
                  </div>
                </button>
              </div>
            </div>
          </Card>
        </div>

        {/* Right Column: Results */}
        <div className="space-y-6">
          {simulationResult ? (
            <>
              {/* Impact Summary */}
              <Card>
                <div className="p-6">
                  <div className="flex items-start justify-between mb-4">
                    <div>
                      <h3 className="text-lg font-semibold">{simulationResult.scenario_name}</h3>
                      <p className="text-sm text-gray-500 capitalize">{simulationResult.scenario_type.replace('_', ' ')}</p>
                    </div>
                    <Badge variant={getRiskLevelColor(simulationResult.risk_level)}>
                      {simulationResult.risk_level} risk
                    </Badge>
                  </div>

                  <div className="grid grid-cols-2 gap-4 mb-6">
                    <div className="p-4 bg-gray-50 rounded-lg border border-gray-200">
                      <div className="text-xs text-gray-500 mb-1 uppercase tracking-wide">Baseline Demand</div>
                      <div className="text-2xl font-bold text-gray-900">{Math.round(simulationResult.total_baseline_demand)}</div>
                      <div className="text-xs text-gray-500 mt-1">units expected normally</div>
                    </div>
                    <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
                      <div className="text-xs text-blue-600 mb-1 uppercase tracking-wide">Scenario Demand</div>
                      <div className="text-2xl font-bold text-blue-900">{Math.round(simulationResult.total_scenario_demand)}</div>
                      <div className="text-xs text-blue-600 mt-1">units with this scenario</div>
                    </div>
                  </div>

                  <div className={`p-5 rounded-xl border-2 ${
                    simulationResult.overall_impact_percent > 0
                      ? 'bg-gradient-to-r from-green-50 to-emerald-50 border-green-200'
                      : 'bg-gradient-to-r from-red-50 to-orange-50 border-red-200'
                  }`}>
                    <div className="flex items-center justify-between">
                      <div>
                        <div className="text-xs font-medium text-gray-600 mb-1 uppercase tracking-wide">Overall Impact</div>
                        <div className="flex items-center gap-2">
                          {simulationResult.overall_impact_percent > 0 ? (
                            <div className="flex items-center gap-1 text-green-700">
                              <ArrowUpRight className="w-6 h-6" />
                              <span className="text-3xl font-bold">
                                +{simulationResult.overall_impact_percent.toFixed(1)}%
                              </span>
                            </div>
                          ) : (
                            <div className="flex items-center gap-1 text-red-700">
                              <ArrowDownRight className="w-6 h-6" />
                              <span className="text-3xl font-bold">
                                {simulationResult.overall_impact_percent.toFixed(1)}%
                              </span>
                            </div>
                          )}
                        </div>
                      </div>
                      <div className={`px-4 py-2 rounded-lg ${
                        simulationResult.overall_impact_percent > 0
                          ? 'bg-green-100 text-green-800'
                          : 'bg-red-100 text-red-800'
                      }`}>
                        <div className="text-xs font-medium">
                          {simulationResult.overall_impact_percent > 0 ? '📈 Increased Demand' : '📉 Decreased Demand'}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </Card>

              {/* Insights */}
              <Card>
                <div className="p-6">
                  <h3 className="text-sm font-semibold mb-4 flex items-center gap-2">
                    <Lightbulb className="w-5 h-5 text-yellow-500" />
                    <span>{t('analytics.scenario_simulation.insights', 'Key Insights')}</span>
                  </h3>
                  <div className="space-y-3">
                    {simulationResult.insights.map((insight, index) => (
                      <div key={index} className="flex items-start gap-3 p-3 bg-blue-50 border border-blue-100 rounded-lg">
                        <CheckCircle className="w-5 h-5 text-blue-600 mt-0.5 flex-shrink-0" />
                        <span className="text-sm text-gray-800">{insight}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </Card>

              {/* Recommendations */}
              <Card>
                <div className="p-6">
                  <h3 className="text-sm font-semibold mb-4 flex items-center gap-2">
                    <TrendingUp className="w-5 h-5 text-green-600" />
                    <span>{t('analytics.scenario_simulation.recommendations', 'Action Plan')}</span>
                  </h3>
                  <div className="space-y-3">
                    {simulationResult.recommendations.map((recommendation, index) => (
                      <div key={index} className="flex items-start gap-3 p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-lg hover:shadow-sm transition-shadow">
                        <div className="flex items-center justify-center w-6 h-6 rounded-full bg-green-600 text-white font-bold text-xs flex-shrink-0">
                          {index + 1}
                        </div>
                        <span className="text-sm text-gray-800 font-medium">{recommendation}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </Card>

              {/* Product Impacts */}
              {simulationResult.product_impacts.length > 0 && (
                <Card>
                  <div className="p-6">
                    <h3 className="text-sm font-semibold mb-4 flex items-center gap-2">
                      <BarChart3 className="w-5 h-5 text-purple-600" />
                      <span>{t('analytics.scenario_simulation.product_impacts', 'Product-Level Impact')}</span>
                    </h3>
                    <div className="space-y-3">
                      {simulationResult.product_impacts.map((impact, index) => {
                        const impactPercent = Math.abs(impact.demand_change_percent);
                        const isPositive = impact.demand_change_percent > 0;

                        return (
                          <div key={index} className={`p-4 border-2 rounded-lg ${
                            isPositive ? 'border-green-200 bg-green-50' : 'border-red-200 bg-red-50'
                          }`}>
                            <div className="flex items-center justify-between mb-3">
                              <div className="flex items-center gap-2">
                                <Package className="w-4 h-4 text-gray-600" />
                                <span className="text-sm font-semibold text-gray-900">
                                  {availableProducts.find(p => p.id === impact.inventory_product_id)?.name || impact.inventory_product_id}
                                </span>
                              </div>
                              <div className={`flex items-center gap-1 px-3 py-1 rounded-full ${
                                isPositive ? 'bg-green-100' : 'bg-red-100'
                              }`}>
                                {isPositive ? (
                                  <ArrowUpRight className="w-4 h-4 text-green-700" />
                                ) : (
                                  <ArrowDownRight className="w-4 h-4 text-red-700" />
                                )}
                                <span className={`text-sm font-bold ${
                                  isPositive ? 'text-green-700' : 'text-red-700'
                                }`}>
                                  {isPositive ? '+' : ''}{impact.demand_change_percent.toFixed(1)}%
                                </span>
                              </div>
                            </div>

                            {/* Visual bar showing demand change */}
                            <div className="mb-2">
                              <div className="flex items-center justify-between text-xs text-gray-600 mb-1">
                                <span>Baseline: {Math.round(impact.baseline_demand)} units</span>
                                <span>Scenario: {Math.round(impact.simulated_demand)} units</span>
                              </div>
                              <div className="w-full h-2 bg-gray-200 rounded-full overflow-hidden">
                                <div
                                  className={`h-full ${isPositive ? 'bg-green-500' : 'bg-red-500'}`}
                                  style={{ width: `${Math.min(impactPercent, 100)}%` }}
                                />
                              </div>
                            </div>

                            {/* Traffic light risk indicator */}
                            <div className="flex items-center gap-2 mt-2">
                              <div className="flex gap-1">
                                <div className={`w-2 h-2 rounded-full ${impactPercent > 30 ? 'bg-red-500' : 'bg-gray-300'}`} />
                                <div className={`w-2 h-2 rounded-full ${impactPercent > 15 && impactPercent <= 30 ? 'bg-yellow-500' : 'bg-gray-300'}`} />
                                <div className={`w-2 h-2 rounded-full ${impactPercent <= 15 ? 'bg-green-500' : 'bg-gray-300'}`} />
                              </div>
                              <span className="text-xs text-gray-600">
                                {impactPercent > 30 ? '🔴 High impact' : impactPercent > 15 ? '🟡 Medium impact' : '🟢 Low impact'}
                              </span>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                </Card>
              )}
            </>
          ) : (
            <Card>
              <div className="p-12 text-center text-gray-400">
                <Sparkles className="w-12 h-12 mx-auto mb-4 opacity-50" />
                <p className="text-sm">
                  {t('analytics.scenario_simulation.no_results', 'Configure and run a scenario to see results')}
                </p>
              </div>
            </Card>
          )}
        </div>
      </div>
    </AnalyticsPageLayout>
  );
};

export default ScenarioSimulationPage;
