import React, {useEffect, useState} from 'react'

import type {LightIndicator, LightScenario} from '../../../generated/ManagingApi'
import {IndicatorType} from '../../../generated/ManagingApi'
import FormInput from '../../mollecules/FormInput/FormInput'
import {useCustomScenario} from '../../../app/store/customScenario'

type ICustomScenario = {
  onCreateScenario: (scenario: LightScenario) => void
  showCustomScenario: boolean
}

const CustomScenario: React.FC<ICustomScenario> = ({
  onCreateScenario,
  showCustomScenario,
}) => {
  const { scenario, setCustomScenario } = useCustomScenario()

  const [name, setName] = useState<string>(scenario?.name || 'Custom Scenario')
  const [loopbackPeriod, setLoopbackPeriod] = useState<number>(scenario?.loopbackPeriod || 1)
  const [indicators, setIndicators] = useState<LightIndicator[]>(scenario?.indicators || [])

  // Available indicator types with their required parameters
  const indicatorTypes = Object.values(IndicatorType).map(type => {
    let params: string[] = [];
    let label = '';

    // Determine required parameters based on indicator type
    switch (type) {
      case IndicatorType.RsiDivergence:
      case IndicatorType.RsiDivergenceConfirm:
      case IndicatorType.EmaTrend:
      case IndicatorType.EmaCross:
      case IndicatorType.StDev:
      case IndicatorType.ThreeWhiteSoldiers:
        params = ['period'];
        break;
        
      case IndicatorType.MacdCross:
        params = ['fastPeriods', 'slowPeriods', 'signalPeriods'];
        break;
        
      case IndicatorType.DualEmaCross:
        params = ['fastPeriods', 'slowPeriods'];
        break;
        
      case IndicatorType.SuperTrend:
      case IndicatorType.SuperTrendCrossEma:
      case IndicatorType.ChandelierExit:
        params = ['period', 'multiplier'];
        break;
        
      case IndicatorType.StochRsiTrend:
        params = ['period', 'stochPeriods', 'signalPeriods', 'smoothPeriods'];
        break;
        
      case IndicatorType.Stc:
      case IndicatorType.LaggingStc:
        params = ['cyclePeriods', 'fastPeriods', 'slowPeriods'];
        break;
        
      case IndicatorType.Composite:
        params = []; // Composite might not need specific parameters
        break;
        
      default:
        params = ['period']; // Default fallback
        break;
    }

    // Create more user-friendly labels
    switch (type) {
      case IndicatorType.RsiDivergence:
        label = 'RSI Divergence';
        break;
      case IndicatorType.RsiDivergenceConfirm:
        label = 'RSI Divergence Confirm';
        break;
      case IndicatorType.MacdCross:
        label = 'MACD Cross';
        break;
      case IndicatorType.EmaCross:
        label = 'EMA Cross';
        break;
      case IndicatorType.DualEmaCross:
        label = 'Dual EMA Cross';
        break;
      case IndicatorType.SuperTrend:
        label = 'Super Trend';
        break;
      case IndicatorType.ChandelierExit:
        label = 'Chandelier Exit';
        break;
      case IndicatorType.EmaTrend:
        label = 'EMA Trend';
        break;
      case IndicatorType.StochRsiTrend:
        label = 'Stoch RSI Trend';
        break;
      case IndicatorType.Stc:
        label = 'STC';
        break;
      case IndicatorType.StDev:
        label = 'Standard Deviation';
        break;
      case IndicatorType.LaggingStc:
        label = 'Lagging STC';
        break;
      case IndicatorType.SuperTrendCrossEma:
        label = 'Super Trend Cross EMA';
        break;
      case IndicatorType.ThreeWhiteSoldiers:
        label = 'Three White Soldiers';
        break;
      case IndicatorType.Composite:
        label = 'Composite';
        break;
      default:
        label = type;
        break;
    }

    return { type, label, params };
  });

  const addIndicator = () => {
    const newIndicator: LightIndicator = {
      name: `Indicator ${indicators.length + 1}`,
      type: indicatorTypes[0].type,
      period: 14,
      fastPeriods: 12,
      slowPeriods: 26,
      signalPeriods: 9,
      multiplier: 3.0,
      stochPeriods: 14,
      smoothPeriods: 3,
      cyclePeriods: 10
    }
    setIndicators([...indicators, newIndicator])
  }

  const removeIndicator = (index: number) => {
    setIndicators(indicators.filter((_, i) => i !== index))
  }

  const updateIndicator = (index: number, field: string, value: any) => {
    const updated = indicators.map((indicator, i) => {
      if (i === index) {
        return { ...indicator, [field]: value }
      }
      return indicator
    })
    setIndicators(updated)
  }

  const handleCreateScenario = () => {
    const scenario: LightScenario = {
      name,
      indicators,
      loopbackPeriod,
    }
    onCreateScenario(scenario)
    setCustomScenario(scenario)
  }

  useEffect(() => {
    handleCreateScenario()
  }, [name, loopbackPeriod, indicators])

  const getRequiredParams = (indicatorType: IndicatorType) => {
    return indicatorTypes.find(t => t.type === indicatorType)?.params || []
  }

  return (
    <>
      {showCustomScenario ? (
        <div className="collapse bg-base-200">
          <input type="checkbox" />
          <div className="collapse-title text-xs font-medium">
            Custom Scenario Builder
          </div>
          <div className="collapse-content">
            <div className="space-y-4">
              {/* Scenario basic info */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormInput label="Scenario Name" htmlFor="scenarioName" inline={false}>
                  <input
                    id="scenarioName"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    type='text'
                    className='input input-bordered w-full'
                    placeholder="Enter scenario name"
                  />
                </FormInput>

                <FormInput label="Lookback Period" htmlFor="loopbackPeriod" inline={false}>
                  <input
                    id="loopbackPeriod"
                    value={loopbackPeriod}
                    onChange={(e) => setLoopbackPeriod(Number(e.target.value))}
                    type='number'
                    min="1"
                    step="1"
                    className='input input-bordered w-full'
                  />
                </FormInput>
              </div>

              {/* Indicators section */}
              <div className="space-y-3">
                <div className="flex justify-between items-center">
                  <h4 className="font-medium">Indicators</h4>
                  <button 
                    type="button"
                    onClick={addIndicator}
                    className="btn btn-sm btn-primary"
                  >
                    Add Indicator
                  </button>
                </div>

                {indicators.map((indicator, index) => (
                  <div key={index} className="border rounded-lg p-4 space-y-3 bg-base-100">
                    <div className="flex justify-between items-start">
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-3 flex-1">
                        <FormInput label="Indicator Name" htmlFor={`indicatorName-${index}`} inline={false}>
                          <input
                            value={indicator.name || ''}
                            onChange={(e) => updateIndicator(index, 'name', e.target.value)}
                            type='text'
                            className='input input-bordered w-full'
                          />
                        </FormInput>

                        <FormInput label="Indicator Type" htmlFor={`indicatorType-${index}`} inline={false}>
                          <select
                            value={indicator.type || indicatorTypes[0].type}
                            onChange={(e) => updateIndicator(index, 'type', e.target.value)}
                            className='select select-bordered w-full'
                          >
                            {indicatorTypes.map((type) => (
                              <option key={type.type} value={type.type}>
                                {type.label}
                              </option>
                            ))}
                          </select>
                        </FormInput>
                      </div>
                      
                      <button 
                        type="button"
                        onClick={() => removeIndicator(index)}
                        className="btn btn-sm btn-error ml-2"
                      >
                        Remove
                      </button>
                    </div>

                    {/* Dynamic parameter inputs based on indicator type */}
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
                      {getRequiredParams(indicator.type || indicatorTypes[0].type).map((param) => (
                        <FormInput key={param} label={param.charAt(0).toUpperCase() + param.slice(1)} htmlFor={`${param}-${index}`} inline={false}>
                          <input
                            value={indicator[param as keyof LightIndicator] as number || ''}
                            onChange={(e) => updateIndicator(index, param, param.includes('multiplier') ? parseFloat(e.target.value) : parseInt(e.target.value))}
                            type='number'
                            step={param.includes('multiplier') ? '0.1' : '1'}
                            min={param.includes('multiplier') ? '0.1' : '1'}
                            className='input input-bordered w-full'
                          />
                        </FormInput>
                      ))}
                    </div>
                  </div>
                ))}

                {indicators.length === 0 && (
                  <div className="text-center text-gray-500 py-4">
                    No indicators added. Click "Add Indicator" to start building your scenario.
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      ) : null}
    </>
  )
}

export default CustomScenario 