import { Fragment, useState, useEffect } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { XMarkIcon } from '@heroicons/react/24/outline';

export interface IndicatorConfig {
  id: string;
  name: string;
  type: 'overlay' | 'panel';
  parameters: Record<string, any>;
  style: {
    color?: string;
    lineWidth?: number;
    lineStyle?: 'solid' | 'dashed' | 'dotted';
  };
}

interface IndicatorSettingsProps {
  isOpen: boolean;
  onClose: () => void;
  indicator: IndicatorConfig | null;
  onSave: (config: IndicatorConfig) => void;
}

const indicatorParameters: Record<string, Array<{ key: string; label: string; type: 'number' | 'select'; min?: number; max?: number; options?: string[] }>> = {
  SMA20: [
    { key: 'period', label: 'Period', type: 'number', min: 1, max: 200 },
  ],
  SMA50: [
    { key: 'period', label: 'Period', type: 'number', min: 1, max: 200 },
  ],
  EMA20: [
    { key: 'period', label: 'Period', type: 'number', min: 1, max: 200 },
  ],
  BB: [
    { key: 'period', label: 'Period', type: 'number', min: 1, max: 200 },
    { key: 'stdDev', label: 'Standard Deviation', type: 'number', min: 0.1, max: 5 },
  ],
  RSI: [
    { key: 'period', label: 'Period', type: 'number', min: 1, max: 100 },
    { key: 'overbought', label: 'Overbought Level', type: 'number', min: 50, max: 100 },
    { key: 'oversold', label: 'Oversold Level', type: 'number', min: 0, max: 50 },
  ],
  MACD: [
    { key: 'fastPeriod', label: 'Fast Period', type: 'number', min: 1, max: 200 },
    { key: 'slowPeriod', label: 'Slow Period', type: 'number', min: 1, max: 200 },
    { key: 'signalPeriod', label: 'Signal Period', type: 'number', min: 1, max: 200 },
  ],
};

const defaultParameters: Record<string, Record<string, any>> = {
  SMA20: { period: 20 },
  SMA50: { period: 50 },
  EMA20: { period: 20 },
  BB: { period: 20, stdDev: 2 },
  RSI: { period: 14, overbought: 70, oversold: 30 },
  MACD: { fastPeriod: 12, slowPeriod: 26, signalPeriod: 9 },
  VWAP: {},
};

const lineStyles = [
  { value: 'solid', label: 'Solid' },
  { value: 'dashed', label: 'Dashed' },
  { value: 'dotted', label: 'Dotted' },
];

export function IndicatorSettings({ isOpen, onClose, indicator, onSave }: IndicatorSettingsProps) {
  const [config, setConfig] = useState<IndicatorConfig | null>(null);

  useEffect(() => {
    if (indicator) {
      setConfig({
        ...indicator,
        parameters: { ...defaultParameters[indicator.id], ...indicator.parameters },
      });
    }
  }, [indicator]);

  if (!config || !indicator) return null;

  const handleParameterChange = (key: string, value: any) => {
    setConfig({
      ...config,
      parameters: {
        ...config.parameters,
        [key]: value,
      },
    });
  };

  const handleStyleChange = (key: string, value: any) => {
    setConfig({
      ...config,
      style: {
        ...config.style,
        [key]: value,
      },
    });
  };

  const handleSave = () => {
    onSave(config);
    onClose();
  };

  const parameters = indicatorParameters[indicator.id] || [];

  return (
    <Transition.Root show={isOpen} as={Fragment}>
      <Dialog as="div" className="relative z-50" onClose={onClose}>
        <Transition.Child
          as={Fragment}
          enter="ease-out duration-300"
          enterFrom="opacity-0"
          enterTo="opacity-100"
          leave="ease-in duration-200"
          leaveFrom="opacity-100"
          leaveTo="opacity-0"
        >
          <div className="fixed inset-0 bg-black/50 transition-opacity" />
        </Transition.Child>

        <div className="fixed inset-0 z-10 overflow-y-auto">
          <div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
            <Transition.Child
              as={Fragment}
              enter="ease-out duration-300"
              enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
              enterTo="opacity-100 translate-y-0 sm:scale-100"
              leave="ease-in duration-200"
              leaveFrom="opacity-100 translate-y-0 sm:scale-100"
              leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
            >
              <Dialog.Panel className="relative transform overflow-hidden rounded-lg bg-surface-secondary text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-md">
                <div className="bg-surface-secondary px-4 pb-4 pt-5 sm:p-6 sm:pb-4">
                  <div className="flex items-center justify-between mb-4">
                    <Dialog.Title as="h3" className="text-lg font-semibold text-text-primary">
                      {config.name} Settings
                    </Dialog.Title>
                    <button
                      onClick={onClose}
                      className="rounded-md text-text-secondary hover:text-text-primary"
                    >
                      <XMarkIcon className="h-5 w-5" />
                    </button>
                  </div>

                  <div className="space-y-4">
                    {/* Parameters */}
                    {parameters.length > 0 && (
                      <div>
                        <h4 className="text-sm font-medium text-text-primary mb-3">Parameters</h4>
                        <div className="space-y-3">
                          {parameters.map(param => (
                            <div key={param.key}>
                              <label className="block text-sm text-text-secondary mb-1">
                                {param.label}
                              </label>
                              {param.type === 'number' ? (
                                <input
                                  type="number"
                                  min={param.min}
                                  max={param.max}
                                  value={config.parameters[param.key] || 0}
                                  onChange={(e) => handleParameterChange(param.key, parseFloat(e.target.value))}
                                  className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
                                />
                              ) : (
                                <select
                                  value={config.parameters[param.key] || ''}
                                  onChange={(e) => handleParameterChange(param.key, e.target.value)}
                                  className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
                                >
                                  {param.options?.map(option => (
                                    <option key={option} value={option}>{option}</option>
                                  ))}
                                </select>
                              )}
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                    {/* Style */}
                    <div>
                      <h4 className="text-sm font-medium text-text-primary mb-3">Style</h4>
                      <div className="space-y-3">
                        <div>
                          <label className="block text-sm text-text-secondary mb-1">Color</label>
                          <div className="flex items-center gap-2">
                            <input
                              type="color"
                              value={config.style.color || '#3b82f6'}
                              onChange={(e) => handleStyleChange('color', e.target.value)}
                              className="w-10 h-10 rounded border border-border cursor-pointer"
                            />
                            <input
                              type="text"
                              value={config.style.color || '#3b82f6'}
                              onChange={(e) => handleStyleChange('color', e.target.value)}
                              className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
                            />
                          </div>
                        </div>

                        <div>
                          <label className="block text-sm text-text-secondary mb-1">Line Width</label>
                          <input
                            type="range"
                            min="1"
                            max="5"
                            value={config.style.lineWidth || 2}
                            onChange={(e) => handleStyleChange('lineWidth', parseInt(e.target.value))}
                            className="w-full"
                          />
                          <div className="text-center text-sm text-text-secondary mt-1">
                            {config.style.lineWidth || 2}px
                          </div>
                        </div>

                        <div>
                          <label className="block text-sm text-text-secondary mb-1">Line Style</label>
                          <select
                            value={config.style.lineStyle || 'solid'}
                            onChange={(e) => handleStyleChange('lineStyle', e.target.value)}
                            className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
                          >
                            {lineStyles.map(style => (
                              <option key={style.value} value={style.value}>{style.label}</option>
                            ))}
                          </select>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="bg-surface-tertiary px-4 py-3 sm:flex sm:flex-row-reverse sm:px-6">
                  <button
                    type="button"
                    className="inline-flex w-full justify-center rounded-md bg-primary-500 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-primary-600 sm:ml-3 sm:w-auto"
                    onClick={handleSave}
                  >
                    Save
                  </button>
                  <button
                    type="button"
                    className="mt-3 inline-flex w-full justify-center rounded-md bg-surface-secondary px-4 py-2 text-sm font-medium text-text-primary shadow-sm ring-1 ring-inset ring-border hover:bg-surface-tertiary sm:mt-0 sm:w-auto"
                    onClick={onClose}
                  >
                    Cancel
                  </button>
                </div>
              </Dialog.Panel>
            </Transition.Child>
          </div>
        </div>
      </Dialog>
    </Transition.Root>
  );
}