import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  TextField,
  Slider,
  Paper,
  IconButton,
  Tooltip,
  Switch,
  Button,
  Grid,
  Select,
  MenuItem,
  FormControl,
} from '@mui/material';
import { Refresh, DragIndicator, Add, Delete } from '@mui/icons-material';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { useChartColors, ChartColorSettings } from '../contexts/ChartColorContext';
import { useIndicatorSettings, IndicatorSettings, CustomReferenceLine } from '../contexts/IndicatorSettingsContext';
import { useIndicatorVisibility, IndicatorVisibilitySettings, IndicatorOrder } from '../contexts/IndicatorVisibilityContext';

// 지표별 색상/굵기 설정 키 매핑
interface ColorConfig {
  label: string;
  colorKey: keyof ChartColorSettings;
  widthKey?: keyof ChartColorSettings;
}

const indicatorColorConfigs: Record<string, ColorConfig[]> = {
  macdLine: [
    { label: 'MACD', colorKey: 'macdLine', widthKey: 'macdLineWidth' },
    { label: '시그널', colorKey: 'signalLine', widthKey: 'signalLineWidth' },
  ],
  rsi: [
    { label: 'RSI', colorKey: 'rsiColor', widthKey: 'rsiWidth' },
    { label: '신호', colorKey: 'rsiSignalColor', widthKey: 'rsiSignalWidth' },
  ],
  stochasticK: [
    { label: '%K', colorKey: 'stochasticK', widthKey: 'stochasticKWidth' },
    { label: '%D', colorKey: 'stochasticD', widthKey: 'stochasticDWidth' },
  ],
  cci: [
    { label: 'CCI', colorKey: 'cciColor', widthKey: 'cciWidth' },
    { label: '신호', colorKey: 'cciSignalColor', widthKey: 'cciSignalWidth' },
  ],
  adx: [{ label: 'ADX', colorKey: 'adxColor', widthKey: 'adxWidth' }],
  plusDi: [
    { label: '+DI', colorKey: 'plusDiColor', widthKey: 'plusDiWidth' },
    { label: '-DI', colorKey: 'minusDiColor', widthKey: 'minusDiWidth' },
  ],
  williamsR: [{ label: 'Williams%R', colorKey: 'williamsRColor', widthKey: 'williamsRWidth' }],
  trix: [
    { label: 'TRIX', colorKey: 'trixColor', widthKey: 'trixWidth' },
    { label: '시그널', colorKey: 'trixSignalColor', widthKey: 'trixSignalWidth' },
  ],
  newPsychological: [{ label: '신심리도', colorKey: 'newPsychologicalColor', widthKey: 'newPsychologicalWidth' }],
  investPsychological: [{ label: '투자심리도', colorKey: 'investPsychologicalColor', widthKey: 'investPsychologicalWidth' }],
  bwi: [{ label: 'BWI', colorKey: 'bwiColor', widthKey: 'bwiWidth' }],
  obv: [
    { label: 'OBV', colorKey: 'obvColor', widthKey: 'obvWidth' },
    { label: '신호', colorKey: 'obvSignalColor', widthKey: 'obvSignalWidth' },
  ],
  volumeOsc: [{ label: 'VolumeOSC', colorKey: 'volumeOscColor', widthKey: 'volumeOscWidth' }],
  vr: [{ label: 'VR', colorKey: 'vrColor', widthKey: 'vrWidth' }],
  disparity: [
    { label: '초단기', colorKey: 'disparityUltraShortColor', widthKey: 'disparityUltraShortWidth' },
    { label: '단기', colorKey: 'disparityShortColor', widthKey: 'disparityShortWidth' },
    { label: '중기', colorKey: 'disparityMidColor', widthKey: 'disparityMidWidth' },
    { label: '장기', colorKey: 'disparityLongColor', widthKey: 'disparityLongWidth' },
  ],
};

// 지표별 파라미터 키 매핑
const indicatorParamKeys: Record<string, { key: string; label: string }[]> = {
  macdLine: [{ key: 'macdFastPeriod', label: '단기 EMA' }, { key: 'macdSlowPeriod', label: '장기 EMA' }, { key: 'macdSignalPeriod', label: '시그널' }],
  rsi: [{ key: 'rsiPeriod', label: '기간' }, { key: 'rsiSignalPeriod', label: '신호' }],
  stochasticK: [{ key: 'stochasticKPeriod', label: '기간' }, { key: 'stochasticSlowing', label: '%K' }, { key: 'stochasticDPeriod', label: '%D' }],
  cci: [{ key: 'cciPeriod', label: '기간' }, { key: 'cciSignalPeriod', label: '신호' }],
  adx: [{ key: 'adxPeriod', label: '기간' }],
  williamsR: [{ key: 'williamsRPeriod', label: '기간' }],
  trix: [{ key: 'trixPeriod', label: '기간' }, { key: 'trixSignalPeriod', label: '시그널' }],
  newPsychological: [{ key: 'newPsychologicalPeriod', label: '기간' }],
  investPsychological: [{ key: 'investPsychologicalPeriod', label: '기간' }],
  bwi: [{ key: 'bwiPeriod', label: '기간' }],
  obv: [{ key: 'obvPeriod', label: '기간' }, { key: 'obvSignalPeriod', label: '신호' }],
  volumeOsc: [{ key: 'volumeOscShortPeriod', label: '단기' }, { key: 'volumeOscLongPeriod', label: '장기' }],
  vr: [{ key: 'vrPeriod', label: '기간' }],
  disparity: [
    { key: 'disparityUltraShortPeriod', label: '초단기' },
    { key: 'disparityShortPeriod', label: '단기' },
    { key: 'disparityMidPeriod', label: '중기' },
    { key: 'disparityLongPeriod', label: '장기' },
  ],
  plusDi: [{ key: 'dmiPeriod', label: '기간' }],
};

// 지표 ID -> 지표 타입 매핑
const indicatorIdToType: Record<string, string> = {
  volume: 'volume',
  macdLine: 'macd',
  rsi: 'rsi',
  stochasticK: 'stochastic',
  cci: 'cci',
  adx: 'adx',
  plusDi: 'dmi',
  williamsR: 'williamsR',
  trix: 'trix',
  disparity: 'disparity',
  newPsychological: 'newPsychological',
  investPsychological: 'investPsychological',
  bwi: 'bwi',
  obv: 'obv',
  volumeOsc: 'volumeOsc',
  vr: 'vr',
};

// Sortable 아이템 컴포넌트 - 테이블 행 스타일
interface SortableItemProps {
  indicator: IndicatorOrder;
  checked: boolean;
  onToggle: () => void;
  colors: ChartColorSettings;
  updateColors: (c: Partial<ChartColorSettings>) => void;
  indicatorSettings: IndicatorSettings;
  updateIndicatorSettings: (s: Partial<IndicatorSettings>) => void;
  getCustomReferenceLines: (indicatorType: string) => CustomReferenceLine[];
  addCustomReferenceLine: (indicatorType: string, line: Omit<CustomReferenceLine, 'id'>) => void;
  removeCustomReferenceLine: (indicatorType: string, lineId: string) => void;
  updateCustomReferenceLine: (indicatorType: string, lineId: string, updates: Partial<CustomReferenceLine>) => void;
}

const SortableItem: React.FC<SortableItemProps> = ({
  indicator,
  checked,
  onToggle,
  colors,
  updateColors,
  indicatorSettings,
  updateIndicatorSettings,
  getCustomReferenceLines,
  addCustomReferenceLine,
  removeCustomReferenceLine,
  updateCustomReferenceLine,
}) => {
  const [expanded, setExpanded] = useState(false);
  const isDisabled = indicator.settingKey === 'volume';
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: indicator.id, disabled: isDisabled });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  const canDrag = !isDisabled;
  const colorConfigs = indicatorColorConfigs[indicator.id] || [];
  const paramKeys = indicatorParamKeys[indicator.id] || [];
  const hasSettings = indicator.settingKey !== 'volume';
  const indicatorType = indicatorIdToType[indicator.id] || indicator.id;
  const referenceLines = getCustomReferenceLines(indicatorType);
  const primaryColor = colorConfigs[0];

  const handleAddReferenceLine = () => {
    addCustomReferenceLine(indicatorType, {
      name: '기준선',
      value: 0,
      color: '#ffeb3b',
      lineStyle: 'dashed',
    });
  };

  // 파라미터와 색상 매핑
  const getColorForParam = (paramIndex: number) => {
    if (paramIndex < colorConfigs.length) {
      return colorConfigs[paramIndex];
    }
    return null;
  };

  return (
    <Box ref={setNodeRef} style={style}>
      {/* 메인 행 */}
      <Paper
        sx={{
          mb: expanded ? 0 : 0.5,
          border: '1px solid',
          borderColor: isDragging ? 'primary.main' : checked ? 'primary.light' : 'divider',
          borderRadius: expanded ? '4px 4px 0 0' : 1,
          bgcolor: isDragging ? 'action.hover' : checked ? 'action.selected' : 'background.paper',
        }}
      >
        <Box
          sx={{
            px: 1.5,
            py: 1,
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            minHeight: 48,
          }}
        >
          {/* 드래그 핸들 */}
          {canDrag ? (
            <Box
              {...attributes}
              {...listeners}
              sx={{ cursor: 'grab', '&:active': { cursor: 'grabbing' }, display: 'flex' }}
            >
              <DragIndicator color="action" sx={{ fontSize: 18 }} />
            </Box>
          ) : (
            <Box sx={{ width: 18 }} />
          )}

          {/* 지표명 */}
          <Typography variant="body2" sx={{ minWidth: 80, fontWeight: checked ? 'bold' : 'normal', fontSize: '13px' }}>
            {indicator.label}
          </Typography>

          {/* 파라미터 + 색상 (이름표시 | 값입력 | 색상버튼) */}
          <Box sx={{ flex: 1, display: 'flex', alignItems: 'center', gap: 1.5, flexWrap: 'wrap' }}>
            {hasSettings && paramKeys.map((param, idx) => {
              const colorCfg = getColorForParam(idx);
              return (
                <Box key={param.key} sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                  {/* 파라미터 이름 */}
                  <Typography variant="caption" sx={{ fontSize: '11px', color: 'text.secondary', minWidth: 28 }}>
                    {param.label}
                  </Typography>
                  {/* 값 입력 */}
                  <TextField
                    type="number"
                    size="small"
                    value={(indicatorSettings as any)[param.key] || ''}
                    onChange={(e) => updateIndicatorSettings({ [param.key]: Number(e.target.value) })}
                    inputProps={{ min: 1, max: 999, style: { fontSize: 11, padding: '4px 6px', textAlign: 'center' } }}
                    sx={{ width: 50, '& .MuiOutlinedInput-root': { bgcolor: 'background.default' } }}
                  />
                  {/* 색상 선택 (있는 경우만) */}
                  {colorCfg && (
                    <Box sx={{ position: 'relative' }}>
                      <Box
                        sx={{
                          width: 24,
                          height: 24,
                          borderRadius: 0.5,
                          bgcolor: colors[colorCfg.colorKey] as string,
                          border: '1px solid',
                          borderColor: 'divider',
                          cursor: 'pointer',
                        }}
                      />
                      <input
                        type="color"
                        value={colors[colorCfg.colorKey] as string || '#666666'}
                        onChange={(e) => updateColors({ [colorCfg.colorKey]: e.target.value })}
                        style={{ position: 'absolute', top: 0, left: 0, width: 24, height: 24, opacity: 0, cursor: 'pointer' }}
                      />
                    </Box>
                  )}
                </Box>
              );
            })}
          </Box>

          {/* 선 굵기 슬라이더 + 미리보기 */}
          {hasSettings && primaryColor?.widthKey && (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, minWidth: 140 }}>
              <Slider
                value={colors[primaryColor.widthKey] as number || 1.5}
                onChange={(_, value) => updateColors({ [primaryColor.widthKey!]: value as number })}
                min={0.5}
                max={5}
                step={0.5}
                size="small"
                sx={{ width: 80 }}
              />
              <Typography variant="caption" sx={{ minWidth: 28, fontSize: '10px' }}>
                {colors[primaryColor.widthKey]}px
              </Typography>
              {/* 미리보기 */}
              <Box
                sx={{
                  width: 30,
                  height: Math.max((colors[primaryColor.widthKey] as number || 1.5) * 2, 2),
                  backgroundColor: colors[primaryColor.colorKey] as string,
                  borderRadius: 0.5,
                }}
              />
            </Box>
          )}

          {/* 우측 끝: ON/OFF 스위치 + 펼침 버튼 */}
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, ml: 'auto' }}>
            <Switch checked={checked} onChange={onToggle} disabled={isDisabled} size="small" />
            {hasSettings ? (
              <IconButton size="small" onClick={() => setExpanded(!expanded)} sx={{ p: 0.25 }}>
                <Typography variant="caption" sx={{ fontSize: '10px', color: 'text.secondary' }}>
                  {expanded ? '▲' : '▼'}
                </Typography>
              </IconButton>
            ) : (
              <Box sx={{ width: 24 }} />
            )}
          </Box>
        </Box>
      </Paper>

      {/* 확장된 기준선 설정 */}
      {expanded && hasSettings && (
        <Paper
          sx={{
            mb: 0.5,
            p: 1.5,
            border: '1px solid',
            borderTop: 'none',
            borderColor: 'divider',
            borderRadius: '0 0 4px 4px',
            bgcolor: 'action.hover',
          }}
        >
          {/* 기준선 헤더 */}
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1 }}>
            <Typography variant="caption" fontWeight="bold" color="text.secondary">
              📏 기준선
            </Typography>
            <Button size="small" startIcon={<Add sx={{ fontSize: 14 }} />} onClick={handleAddReferenceLine} sx={{ fontSize: '10px', py: 0 }}>
              추가
            </Button>
          </Box>

          {referenceLines.length > 0 ? (
            <>
              {/* 기준선 테이블 헤더 */}
              <Box sx={{ p: 0.5, mb: 0.5, bgcolor: 'primary.main', borderRadius: 0.5, opacity: 0.85 }}>
                <Grid container spacing={0.5} alignItems="center">
                  <Grid item xs={3}>
                    <Typography variant="caption" fontWeight="bold" color="white" sx={{ fontSize: '10px' }}>이름</Typography>
                  </Grid>
                  <Grid item xs={2}>
                    <Typography variant="caption" fontWeight="bold" color="white" sx={{ fontSize: '10px' }}>값</Typography>
                  </Grid>
                  <Grid item xs={2}>
                    <Typography variant="caption" fontWeight="bold" color="white" sx={{ fontSize: '10px' }}>색상</Typography>
                  </Grid>
                  <Grid item xs={3}>
                    <Typography variant="caption" fontWeight="bold" color="white" sx={{ fontSize: '10px' }}>선 종류</Typography>
                  </Grid>
                  <Grid item xs={2}>
                    <Typography variant="caption" fontWeight="bold" color="white" sx={{ fontSize: '10px' }}>삭제</Typography>
                  </Grid>
                </Grid>
              </Box>

              {/* 기준선 행 */}
              {referenceLines.map((line) => (
                <Box key={line.id} sx={{ p: 0.5, mb: 0.5, bgcolor: 'background.paper', borderRadius: 0.5, border: '1px solid', borderColor: 'divider' }}>
                  <Grid container spacing={0.5} alignItems="center">
                    <Grid item xs={3}>
                      <TextField
                        size="small"
                        fullWidth
                        value={line.name}
                        onChange={(e) => updateCustomReferenceLine(indicatorType, line.id, { name: e.target.value })}
                        inputProps={{ style: { fontSize: 10, padding: '4px 6px' } }}
                      />
                    </Grid>
                    <Grid item xs={2}>
                      <TextField
                        size="small"
                        fullWidth
                        type="number"
                        value={line.value}
                        onChange={(e) => updateCustomReferenceLine(indicatorType, line.id, { value: parseFloat(e.target.value) || 0 })}
                        inputProps={{ style: { fontSize: 10, padding: '4px 6px', textAlign: 'center' } }}
                      />
                    </Grid>
                    <Grid item xs={2}>
                      <Box sx={{ position: 'relative' }}>
                        <Box sx={{ width: 20, height: 20, borderRadius: 0.5, bgcolor: line.color, border: '1px solid', borderColor: 'divider', cursor: 'pointer' }} />
                        <input
                          type="color"
                          value={line.color}
                          onChange={(e) => updateCustomReferenceLine(indicatorType, line.id, { color: e.target.value })}
                          style={{ position: 'absolute', top: 0, left: 0, width: 20, height: 20, opacity: 0, cursor: 'pointer' }}
                        />
                      </Box>
                    </Grid>
                    <Grid item xs={3}>
                      <FormControl size="small" fullWidth>
                        <Select
                          value={line.lineStyle || 'dashed'}
                          onChange={(e) => updateCustomReferenceLine(indicatorType, line.id, { lineStyle: e.target.value as 'solid' | 'dashed' | 'dotted' })}
                          sx={{ fontSize: '10px', '& .MuiSelect-select': { py: 0.5, px: 0.5 } }}
                        >
                          <MenuItem value="solid" sx={{ fontSize: '10px' }}>실선</MenuItem>
                          <MenuItem value="dashed" sx={{ fontSize: '10px' }}>점선</MenuItem>
                          <MenuItem value="dotted" sx={{ fontSize: '10px' }}>점점선</MenuItem>
                        </Select>
                      </FormControl>
                    </Grid>
                    <Grid item xs={2}>
                      <IconButton size="small" onClick={() => removeCustomReferenceLine(indicatorType, line.id)} color="error" sx={{ p: 0.25 }}>
                        <Delete sx={{ fontSize: 16 }} />
                      </IconButton>
                    </Grid>
                  </Grid>
                </Box>
              ))}
            </>
          ) : (
            <Typography variant="caption" color="text.disabled" sx={{ display: 'block', textAlign: 'center', py: 0.5 }}>
              기준선이 없습니다
            </Typography>
          )}
        </Paper>
      )}
    </Box>
  );
};

const IndicatorSettingsPanel: React.FC = () => {
  const { colors, updateColors, resetColors } = useChartColors();
  const { 
    indicatorSettings, 
    updateIndicatorSettings, 
    resetIndicatorSettings,
    getCustomReferenceLines,
    addCustomReferenceLine,
    removeCustomReferenceLine,
    updateCustomReferenceLine,
  } = useIndicatorSettings();
  const { settings, order, updateSettings, updateOrder, resetSettings } = useIndicatorVisibility();

  const [localOrder, setLocalOrder] = useState<IndicatorOrder[]>(order);

  useEffect(() => {
    setLocalOrder(order);
  }, [order]);

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  );

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (over && active.id !== over.id) {
      const oldIndex = localOrder.findIndex((item) => item.id === active.id);
      const newIndex = localOrder.findIndex((item) => item.id === over.id);
      const newOrder = arrayMove(localOrder, oldIndex, newIndex);
      setLocalOrder(newOrder);
      updateOrder(newOrder);
    }
  };

  const handleToggle = (key: keyof IndicatorVisibilitySettings) => {
    if (key === 'candleChart') return;
    
    if (key === 'macdLine') {
      updateSettings({ macdLine: !settings.macdLine, macdHistogram: !settings.macdLine });
    } else if (key === 'stochasticK') {
      updateSettings({ stochasticK: !settings.stochasticK, stochasticD: !settings.stochasticK, stochasticSlow: !settings.stochasticK });
    } else if (key === 'plusDi') {
      updateSettings({ plusDi: !settings.plusDi, minusDi: !settings.plusDi });
    } else if (key === 'trix') {
      updateSettings({ trix: !settings.trix, trixSignal: !settings.trix });
    } else {
      updateSettings({ [key]: !settings[key] });
    }
  };

  const handleReset = () => {
    resetSettings();
    resetColors();
    resetIndicatorSettings();
  };

  // 필터링된 지표 목록
  const filteredOrder = localOrder.filter(item => 
    item.settingKey !== 'candleChart' &&
    item.settingKey !== 'stochasticD' &&
    item.settingKey !== 'stochasticSlow' &&
    item.settingKey !== 'trixSignal' &&
    item.settingKey !== 'minusDi' &&
    item.settingKey !== 'macdHistogram'
  );

  return (
    <Box>
      {/* 헤더 */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
        <Typography variant="subtitle1" fontWeight="bold">
          📈 보조지표 설정
        </Typography>
        <Tooltip title="모두 초기화">
          <Button startIcon={<Refresh />} onClick={handleReset} size="small" color="inherit">
            초기화
          </Button>
        </Tooltip>
      </Box>

      <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 1.5 }}>
        지표를 드래그하여 순서를 변경하고, ▼를 클릭하여 기준선을 설정할 수 있습니다.
      </Typography>

      {/* 지표 목록 */}
      <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
        <SortableContext items={filteredOrder.map(i => i.id)} strategy={verticalListSortingStrategy}>
          {filteredOrder.map((indicator) => (
            <SortableItem
              key={indicator.id}
              indicator={indicator}
              checked={Boolean(settings[indicator.settingKey])}
              onToggle={() => handleToggle(indicator.settingKey)}
              colors={colors}
              updateColors={updateColors}
              indicatorSettings={indicatorSettings}
              updateIndicatorSettings={updateIndicatorSettings}
              getCustomReferenceLines={getCustomReferenceLines}
              addCustomReferenceLine={addCustomReferenceLine}
              removeCustomReferenceLine={removeCustomReferenceLine}
              updateCustomReferenceLine={updateCustomReferenceLine}
            />
          ))}
        </SortableContext>
      </DndContext>
    </Box>
  );
};

export default IndicatorSettingsPanel;
