import React, { useState } from 'react';
import {
  Box,
  Typography,
  Switch,
  Divider,
  Alert,
  Paper,
  Button,
  Chip,
  TextField,
  Slider,
  FormControlLabel,
} from '@mui/material';
import { DragIndicator, RestartAlt, Settings } from '@mui/icons-material';
import { useChartColors, ChartColorSettings } from '../../contexts/ChartColorContext';
import { useIndicatorSettings, IndicatorSettings } from '../../contexts/IndicatorSettingsContext';
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 { useIndicatorVisibility, IndicatorVisibilitySettings, IndicatorOrder } from '../../contexts/IndicatorVisibilityContext';
import { useAuth } from '../../contexts/AuthContext';
import MASettingsDialog from '../MASettingsDialog';
import IchimokuSettingsDialog from '../IchimokuSettingsDialog';

// 지표별 색상/굵기 설정 키 매핑 (여러 색상 지원)
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: '', colorKey: 'rsiColor', widthKey: 'rsiWidth' }],
  stochasticK: [
    { label: '%K', colorKey: 'stochasticK', widthKey: 'stochasticKWidth' },
    { label: '%D', colorKey: 'stochasticD', widthKey: 'stochasticDWidth' },
  ],
  cci: [{ label: '', colorKey: 'cciColor', widthKey: 'cciWidth' }],
  adx: [{ label: '', colorKey: 'adxColor', widthKey: 'adxWidth' }],
  plusDi: [
    { label: '+DI', colorKey: 'plusDiColor', widthKey: 'plusDiWidth' },
    { label: '-DI', colorKey: 'minusDiColor', widthKey: 'minusDiWidth' },
  ],
  minusDi: [],
  williamsR: [{ label: '', 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: '', colorKey: 'bwiColor', widthKey: 'bwiWidth' }],
  obv: [{ label: '', colorKey: 'obvColor', widthKey: 'obvWidth' }],
  volumeOsc: [{ label: '', colorKey: 'volumeOscColor', widthKey: 'volumeOscWidth' }],
  vr: [{ label: '', 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, string[]> = {
  macdLine: ['macdFastPeriod', 'macdSlowPeriod', 'macdSignalPeriod'],
  rsi: ['rsiPeriod'],
  stochasticK: ['stochasticKPeriod', 'stochasticDPeriod', 'stochasticSlowing'],
  cci: ['cciPeriod', 'cciSignalPeriod'],
  adx: ['adxPeriod'],
  williamsR: ['williamsRPeriod'],
  trix: ['trixPeriod', 'trixSignalPeriod'],
  newPsychological: ['newPsychologicalPeriod'],
  investPsychological: ['investPsychologicalPeriod'],
  bwi: ['bwiPeriod'],
  obv: ['obvPeriod'],
  volumeOsc: ['volumeOscShortPeriod', 'volumeOscLongPeriod'],
  vr: ['vrPeriod'],
  disparity: ['disparityUltraShortPeriod', 'disparityShortPeriod', 'disparityMidPeriod', 'disparityLongPeriod'],
  plusDi: ['dmiPeriod'],
  minusDi: ['dmiPeriod'],
};

// Sortable 아이템 컴포넌트
interface SortableItemProps {
  indicator: IndicatorOrder;
  isDisabled: boolean;
  checked: boolean;
  onToggle: () => void;
  colors: ChartColorSettings;
  updateColors: (newColors: Partial<ChartColorSettings>) => void;
  indicatorSettings: IndicatorSettings;
  updateIndicatorSettings: (newSettings: Partial<IndicatorSettings>) => void;
}

const SortableItem: React.FC<SortableItemProps> = ({ 
  indicator, 
  isDisabled, 
  checked, 
  onToggle,
  colors,
  updateColors,
  indicatorSettings,
  updateIndicatorSettings,
}) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: indicator.id, disabled: isDisabled || indicator.settingKey === 'candleChart' });

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

  const canDrag = !isDisabled && indicator.settingKey !== 'candleChart';
  const colorConfigs = indicatorColorConfigs[indicator.id] || [];
  const paramKeys = indicatorParamKeys[indicator.id];
  const hasSettings = indicator.settingKey !== 'candleChart' && indicator.settingKey !== 'volume';
  const primaryColor = colorConfigs[0];
  const secondaryColors = colorConfigs.slice(1);

  return (
    <Paper
      ref={setNodeRef}
      style={style}
      sx={{
        mb: 1,
        border: '1px solid',
        borderColor: checked ? 'primary.main' : 'divider',
        borderRadius: 1,
        bgcolor: isDragging ? 'action.hover' : checked ? 'action.selected' : 'background.paper',
        opacity: checked ? 1 : 0.7,
      }}
    >
      <Box sx={{ 
        px: 1.5, 
        py: 1.2, 
        display: 'flex', 
        alignItems: 'center',
        gap: 1.5,
        minHeight: 48,
      }}>
        {/* 사용 스위치 */}
        <Box sx={{ width: 50, display: 'flex', justifyContent: 'center' }}>
          <Switch
            checked={checked}
            onChange={onToggle}
            disabled={isDisabled}
            size="small"
          />
        </Box>

        {/* 드래그 핸들 + 지표명 */}
        <Box sx={{ width: 120, display: 'flex', alignItems: 'center', gap: 0.5 }}>
          {canDrag && (
            <Box
              {...attributes}
              {...listeners}
              sx={{ cursor: 'grab', '&:active': { cursor: 'grabbing' }, display: 'flex' }}
            >
              <DragIndicator color="action" sx={{ fontSize: 18 }} />
            </Box>
          )}
          <Typography variant="body2" sx={{ fontWeight: checked ? 'bold' : 'normal', fontSize: '13px' }}>
            {indicator.label}
          </Typography>
        </Box>

        {/* 파라미터 영역 */}
        <Box sx={{ width: 200, display: 'flex', alignItems: 'center', gap: 0.5 }}>
          {hasSettings && paramKeys && paramKeys.map((paramKey) => (
            <TextField
              key={paramKey}
              type="number"
              size="small"
              value={(indicatorSettings as any)[paramKey] || ''}
              onChange={(e) => updateIndicatorSettings({ [paramKey]: Number(e.target.value) })}
              disabled={!checked}
              inputProps={{ min: 1, max: 999, style: { fontSize: 12, padding: '6px 8px', textAlign: 'center' } }}
              sx={{ 
                width: paramKeys.length > 2 ? 55 : 65,
                '& .MuiOutlinedInput-root': { bgcolor: 'background.default' },
              }}
            />
          ))}
        </Box>

        {/* 색상 영역 */}
        <Box sx={{ width: 120, display: 'flex', alignItems: 'center', gap: 1 }}>
          {hasSettings && primaryColor && (
            <Box sx={{ position: 'relative' }}>
              <Box
                sx={{
                  width: 32,
                  height: 32,
                  borderRadius: 1,
                  bgcolor: colors[primaryColor.colorKey] as string,
                  border: '2px solid',
                  borderColor: 'divider',
                  cursor: checked ? 'pointer' : 'default',
                  opacity: checked ? 1 : 0.5,
                }}
              />
              <input
                type="color"
                value={colors[primaryColor.colorKey] as string || '#666666'}
                onChange={(e) => updateColors({ [primaryColor.colorKey]: e.target.value })}
                disabled={!checked}
                style={{ position: 'absolute', top: 0, left: 0, width: 32, height: 32, opacity: 0, cursor: 'pointer' }}
              />
            </Box>
          )}
          {/* 추가 색상 (시그널 등) */}
          {hasSettings && secondaryColors.map((cfg) => (
            <Box key={cfg.colorKey} sx={{ position: 'relative' }}>
              <Box
                sx={{
                  width: 24,
                  height: 24,
                  borderRadius: 0.5,
                  bgcolor: colors[cfg.colorKey] as string,
                  border: '1px solid',
                  borderColor: 'divider',
                  cursor: checked ? 'pointer' : 'default',
                  opacity: checked ? 1 : 0.5,
                }}
              />
              <input
                type="color"
                value={colors[cfg.colorKey] as string || '#666666'}
                onChange={(e) => updateColors({ [cfg.colorKey]: e.target.value })}
                disabled={!checked}
                style={{ position: 'absolute', top: 0, left: 0, width: 24, height: 24, opacity: 0, cursor: 'pointer' }}
              />
            </Box>
          ))}
        </Box>

        {/* 선 굵기 영역 */}
        <Box sx={{ flex: 1, display: 'flex', alignItems: 'center', gap: 1 }}>
          {hasSettings && primaryColor?.widthKey && (
            <>
              <Slider
                value={colors[primaryColor.widthKey] as number || 1}
                onChange={(_, value) => updateColors({ [primaryColor.widthKey!]: value as number })}
                disabled={!checked}
                min={0.5}
                max={5}
                step={0.5}
                sx={{ flex: 1, maxWidth: 150 }}
                size="small"
              />
              <Typography variant="caption" sx={{ minWidth: 30, fontSize: '11px', color: 'text.secondary' }}>
                {colors[primaryColor.widthKey]}px
              </Typography>
              {/* 선 미리보기 */}
              <Box
                sx={{
                  width: 40,
                  height: Math.max((colors[primaryColor.widthKey] as number || 1) * 2, 2),
                  bgcolor: checked ? colors[primaryColor.colorKey] as string : 'grey.400',
                  borderRadius: 0.5,
                }}
              />
            </>
          )}
        </Box>
      </Box>
    </Paper>
  );
};

const IndicatorVisibilityTab: React.FC = () => {
  const { isAuthenticated } = useAuth();
  const { settings, order, updateSettings, updateOrder, saveSettings, resetSettings } = useIndicatorVisibility();
  const { colors, updateColors } = useChartColors();
  const { indicatorSettings, updateIndicatorSettings } = useIndicatorSettings();
  const [tempSettings, setTempSettings] = useState<IndicatorVisibilitySettings>(settings);
  const [tempOrder, setTempOrder] = useState<IndicatorOrder[]>(order);
  const [success, setSuccess] = useState(false);
  const [maSettingsDialogOpen, setMaSettingsDialogOpen] = useState(false);
  const [ichimokuSettingsDialogOpen, setIchimokuSettingsDialogOpen] = useState(false);

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

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;

    if (over && active.id !== over.id) {
      const oldIndex = tempOrder.findIndex((item) => item.id === active.id);
      const newIndex = tempOrder.findIndex((item) => item.id === over.id);

      const newOrder = arrayMove(tempOrder, oldIndex, newIndex);
      setTempOrder(newOrder);
      updateOrder(newOrder);
    }
  };

  const handleToggle = (settingKey: string) => {
    if (settingKey === 'candleChart' || settingKey === 'volume') {
      return;
    }

    const newSettings = {
      ...tempSettings,
      [settingKey]: !tempSettings[settingKey as keyof IndicatorVisibilitySettings],
    };
    setTempSettings(newSettings);
    updateSettings(newSettings);
  };

  const handleSave = async () => {
    await saveSettings(isAuthenticated);
    setSuccess(true);
    setTimeout(() => setSuccess(false), 2000);
  };

  const handleReset = () => {
    if (window.confirm('모든 보조지표 설정을 초기화하시겠습니까?')) {
      resetSettings();
      setTempSettings(settings);
      setTempOrder(order);
      setSuccess(true);
      setTimeout(() => setSuccess(false), 2000);
    }
  };

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h6">
          보조지표 표시 설정 (15가지)
        </Typography>
        <Button
          variant="outlined"
          size="small"
          startIcon={<RestartAlt />}
          onClick={handleReset}
          color="secondary"
        >
          초기화
        </Button>
      </Box>

      {success && (
        <Alert severity="success" sx={{ mb: 2 }}>
          설정이 저장되었습니다.
        </Alert>
      )}

      <Alert severity="info" sx={{ mb: 3 }}>
        <Typography variant="body2">
          • 표시할 보조지표를 선택하고 드래그하여 순서를 변경할 수 있습니다.
        </Typography>
        <Typography variant="body2">
          • 캔들차트와 거래량은 항상 표시됩니다.
        </Typography>
        <Typography variant="body2">
          • 15가지 보조지표: 신심리도, 투자심리도, MACD, CCI, ADX, BWI, DMI, OBV, RSI, Stochastic Slow, Williams %R, TRIX, VolumeOSC, VR, 이격도
        </Typography>
      </Alert>

      {/* 헤더 행 - 이동평균선 설정과 동일한 스타일 */}
      <Paper sx={{ p: 1.5, mb: 2, bgcolor: 'primary.main', opacity: 0.9 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
          <Box sx={{ width: 50, textAlign: 'center' }}>
            <Typography variant="caption" fontWeight="bold" color="white">사용</Typography>
          </Box>
          <Box sx={{ width: 120 }}>
            <Typography variant="caption" fontWeight="bold" color="white">이름</Typography>
          </Box>
          <Box sx={{ width: 200 }}>
            <Typography variant="caption" fontWeight="bold" color="white">파라미터</Typography>
          </Box>
          <Box sx={{ width: 120 }}>
            <Typography variant="caption" fontWeight="bold" color="white">색상</Typography>
          </Box>
          <Box sx={{ flex: 1 }}>
            <Typography variant="caption" fontWeight="bold" color="white">선 굵기</Typography>
          </Box>
        </Box>
      </Paper>

      <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
        <SortableContext items={tempOrder.map((item) => item.id)} strategy={verticalListSortingStrategy}>
          {tempOrder.map((indicator) => {
            const settingKey = indicator.settingKey as keyof IndicatorVisibilitySettings;
            const isDisabled = settingKey === 'candleChart' || settingKey === 'volume';
            const value = tempSettings[settingKey];
            const checked = typeof value === 'boolean' ? value : false;

            return (
              <SortableItem
                key={indicator.id}
                indicator={indicator}
                isDisabled={isDisabled}
                checked={checked}
                onToggle={() => handleToggle(settingKey)}
                colors={colors}
                updateColors={updateColors}
                indicatorSettings={indicatorSettings}
                updateIndicatorSettings={updateIndicatorSettings}
              />
            );
          })}
        </SortableContext>
      </DndContext>

      <Divider sx={{ my: 3 }} />

      {/* 이동평균선 설정 (캔들차트 오버레이) */}
      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 'bold', mb: 2 }}>
          📈 이동평균선 (캔들차트 오버레이)
        </Typography>
        <Alert severity="info" sx={{ mb: 2 }}>
          <Typography variant="body2">
            이동평균선은 캔들차트 위에 오버레이로 표시됩니다. 기간, 색상, 선 굵기를 자유롭게 설정할 수 있습니다.
          </Typography>
        </Alert>
        
        {/* 현재 활성화된 MA 요약 */}
        <Paper sx={{ p: 2, mb: 2 }}>
          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, mb: 2 }}>
            {settings.maLines?.map((ma) => (
              <Chip
                key={ma.id}
                label={`${ma.id}(${ma.period})`}
                size="small"
                variant={ma.enabled ? "filled" : "outlined"}
                sx={{
                  backgroundColor: ma.enabled ? ma.color : 'transparent',
                  color: ma.enabled ? '#fff' : 'text.secondary',
                  borderColor: ma.color,
                  fontWeight: ma.enabled ? 'bold' : 'normal',
                  '& .MuiChip-label': {
                    textShadow: ma.enabled ? '0 1px 2px rgba(0,0,0,0.5)' : 'none',
                  },
                }}
              />
            ))}
          </Box>
          <Typography variant="caption" color="text.secondary">
            {settings.maLines?.filter(ma => ma.enabled).length || 0}개 활성화됨
          </Typography>
        </Paper>

        {/* 설정 버튼 */}
        <Button
          variant="outlined"
          startIcon={<Settings />}
          onClick={() => setMaSettingsDialogOpen(true)}
          fullWidth
          sx={{ py: 1.5 }}
        >
          이동평균선 상세 설정
        </Button>
      </Box>

      {/* 이동평균선 설정 다이얼로그 */}
      <MASettingsDialog 
        open={maSettingsDialogOpen} 
        onClose={() => setMaSettingsDialogOpen(false)} 
      />

      <Divider sx={{ my: 3 }} />

      {/* 일목균형표 설정 (캔들차트 오버레이) */}
      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 'bold', mb: 2 }}>
          ☁️ 일목균형표 (캔들차트 오버레이)
        </Typography>
        <Alert severity="info" sx={{ mb: 2 }}>
          <Typography variant="body2">
            일목균형표는 캔들차트 위에 오버레이로 표시됩니다.
          </Typography>
        </Alert>
        <Paper sx={{ p: 1.5, mb: 1 }}>
          <FormControlLabel
            control={
              <Switch
                checked={tempSettings.ichimokuTenkan || false}
                onChange={() => handleToggle('ichimokuTenkan')}
              />
            }
            label={
              <Box>
                <Typography variant="body1" sx={{ fontWeight: tempSettings.ichimokuTenkan ? 600 : 400 }}>
                  전환선 (9일)
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  단기 추세를 나타내는 선
                </Typography>
              </Box>
            }
          />
        </Paper>
        <Paper sx={{ p: 1.5, mb: 1 }}>
          <FormControlLabel
            control={
              <Switch
                checked={tempSettings.ichimokuKijun || false}
                onChange={() => handleToggle('ichimokuKijun')}
              />
            }
            label={
              <Box>
                <Typography variant="body1" sx={{ fontWeight: tempSettings.ichimokuKijun ? 600 : 400 }}>
                  기준선 (26일)
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  중기 추세를 나타내는 선
                </Typography>
              </Box>
            }
          />
        </Paper>
        <Paper sx={{ p: 1.5, mb: 1 }}>
          <FormControlLabel
            control={
              <Switch
                checked={tempSettings.ichimokuChikou || false}
                onChange={() => handleToggle('ichimokuChikou')}
              />
            }
            label={
              <Box>
                <Typography variant="body1" sx={{ fontWeight: tempSettings.ichimokuChikou ? 600 : 400 }}>
                  후행스팬
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  현재 종가를 26일 전에 표시
                </Typography>
              </Box>
            }
          />
        </Paper>
        <Paper sx={{ p: 1.5, mb: 1 }}>
          <FormControlLabel
            control={
              <Switch
                checked={tempSettings.ichimokuSenkouA || false}
                onChange={() => handleToggle('ichimokuSenkouA')}
              />
            }
            label={
              <Box>
                <Typography variant="body1" sx={{ fontWeight: tempSettings.ichimokuSenkouA ? 600 : 400 }}>
                  선행스팬1 + 구름
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  (전환선+기준선)/2를 26일 앞으로 표시
                </Typography>
              </Box>
            }
          />
        </Paper>
        <Paper sx={{ p: 1.5 }}>
          <FormControlLabel
            control={
              <Switch
                checked={tempSettings.ichimokuSenkouB || false}
                onChange={() => handleToggle('ichimokuSenkouB')}
              />
            }
            label={
              <Box>
                <Typography variant="body1" sx={{ fontWeight: tempSettings.ichimokuSenkouB ? 600 : 400 }}>
                  선행스팬2 + 구름
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  52일 중간값을 26일 앞으로 표시
                </Typography>
              </Box>
            }
          />
        </Paper>
        <Button
          variant="outlined"
          startIcon={<Settings />}
          onClick={() => setIchimokuSettingsDialogOpen(true)}
          sx={{ width: '100%', mt: 2 }}
        >
          일목균형표 상세 설정 (색상/굵기)
        </Button>
      </Box>

      {/* 일목균형표 설정 다이얼로그 */}
      <IchimokuSettingsDialog
        open={ichimokuSettingsDialogOpen}
        onClose={() => setIchimokuSettingsDialogOpen(false)}
      />

      <Divider sx={{ my: 3 }} />

      <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
        <Button variant="contained" onClick={handleSave}>
          저장
        </Button>
      </Box>
    </Box>
  );
};

export default IndicatorVisibilityTab;
