import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Autocomplete,
  TextField,
  Button,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  IconButton,
  Chip,
  CircularProgress,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Divider,
  Paper,
} from '@mui/material';
import {
  Add as AddIcon,
  Delete as DeleteIcon,
  CheckCircle as CheckCircleIcon,
  Info as InfoIcon,
  Close as CloseIcon,
} from '@mui/icons-material';
import { getStrategyRules, StrategyRuleDto } from '../../services/strategyRuleApi';
import {
  getAllAlertStrategies,
  addAlertStrategy,
  deleteAlertStrategy,
  AlertStrategyDto,
} from '../../services/alertStrategyApi';

/**
 * 알림 조건 (전략 목록) 패널
 */
const AlertStrategyPanel: React.FC = () => {
  const [strategies, setStrategies] = useState<StrategyRuleDto[]>([]);
  const [alertStrategies, setAlertStrategies] = useState<AlertStrategyDto[]>([]);
  const [selectedStrategy, setSelectedStrategy] = useState<StrategyRuleDto | null>(null);
  const [loading, setLoading] = useState(true);
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);
  const [detailStrategy, setDetailStrategy] = useState<StrategyRuleDto | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);

  useEffect(() => {
    loadStrategies();
    loadAlertStrategies();
  }, []);

  const loadStrategies = async () => {
    try {
      console.log('[Alert Strategy] 전략 목록 로드 시작 (BUY, enabled=true)');
      // BUY 신호 전략만 조회
      const strategyList = await getStrategyRules('BUY', true);
      console.log('[Alert Strategy] 전략 목록 로드 완료:', {
        count: strategyList.length,
        strategies: strategyList.map(s => ({ id: s.id, name: s.name }))
      });
      setStrategies(strategyList);
    } catch (error) {
      console.error('[Alert Strategy] 전략 목록 로드 실패:', error);
    }
  };

  const loadAlertStrategies = async () => {
    try {
      setLoading(true);
      console.log('[Alert Strategy] 알림 전략 목록 로드 시작');
      const alertStrategyList = await getAllAlertStrategies();
      console.log('[Alert Strategy] 알림 전략 목록 로드 완료:', {
        count: alertStrategyList.length,
        strategies: alertStrategyList.map(s => ({ id: s.id, strategyRuleId: s.strategyRuleId, name: s.strategyRuleName }))
      });
      setAlertStrategies(alertStrategyList);
    } catch (error) {
      console.error('[Alert Strategy] 알림 전략 목록 로드 실패:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = async () => {
    if (!selectedStrategy) {
      console.warn('[Alert Strategy] 선택된 전략이 없습니다');
      return;
    }
    
    if (!selectedStrategy.id) {
      console.error('[Alert Strategy] 전략 ID가 없습니다:', selectedStrategy);
      alert('전략 ID가 없습니다. 전략 목록을 다시 불러오세요.');
      return;
    }

    try {
      console.log('[Alert Strategy] 추가 요청:', {
        strategyId: selectedStrategy.id,
        strategyName: selectedStrategy.name
      });
      
      await addAlertStrategy(selectedStrategy.id);
      await loadAlertStrategies();
      setSelectedStrategy(null);
      
      console.log('[Alert Strategy] 추가 성공');
      alert('알림 전략이 추가되었습니다.');
      
      // 전략 화면에 알림 상태 변경 알림 (커스텀 이벤트)
      window.dispatchEvent(new CustomEvent('alertStrategyChanged'));
    } catch (error: any) {
      console.error('[Alert Strategy] 추가 실패:', error);
      console.error('[Alert Strategy] 에러 상세:', {
        message: error.message,
        response: error.response?.data,
        status: error.response?.status,
        statusText: error.response?.statusText
      });
      
      const errorMessage = error.response?.data?.message 
        || error.response?.data 
        || error.message 
        || '알림 전략 추가에 실패했습니다.';
      
      alert(`알림 전략 추가 실패:\n${errorMessage}`);
    }
  };

  const handleDelete = async (id: number) => {
    if (!window.confirm('이 알림 조건을 삭제하시겠습니까?')) return;

    try {
      await deleteAlertStrategy(id);
      await loadAlertStrategies();
      
      // 전략 화면에 알림 상태 변경 알림 (커스텀 이벤트)
      window.dispatchEvent(new CustomEvent('alertStrategyChanged'));
    } catch (error) {
      console.error('알림 전략 삭제 실패:', error);
      alert('알림 전략 삭제에 실패했습니다.');
    }
  };

  const handleShowDetail = async (strategyRuleId: number) => {
    try {
      setDetailLoading(true);
      setDetailDialogOpen(true);
      
      // 전략 상세 정보 조회
      const strategyDetail = strategies.find(s => s.id === strategyRuleId);
      if (strategyDetail) {
        setDetailStrategy(strategyDetail);
      } else {
        // 전략 목록에 없으면 API로 다시 조회
        const allStrategies = await getStrategyRules();
        const foundStrategy = allStrategies.find(s => s.id === strategyRuleId);
        setDetailStrategy(foundStrategy || null);
      }
    } catch (error) {
      console.error('전략 상세 정보 로드 실패:', error);
      alert('전략 상세 정보를 불러오는데 실패했습니다.');
    } finally {
      setDetailLoading(false);
    }
  };

  const handleCloseDetail = () => {
    setDetailDialogOpen(false);
    setDetailStrategy(null);
  };

  // 이미 추가된 전략 제외
  const availableStrategies = strategies.filter(
    (strategy) => !alertStrategies.some((as) => as.strategyRuleId === strategy.id)
  );

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <Typography variant="h6" gutterBottom sx={{ fontSize: { xs: '1rem', sm: '1.25rem' } }}>
        알림 조건 (전략 목록)
      </Typography>
      <Typography variant="body2" color="text.secondary" sx={{ mb: 2, fontSize: { xs: '0.8rem', sm: '0.875rem' } }}>
        알림으로 체크할 전략을 추가하세요. 활성화된 종목에 대해 추가된 전략 조건을 체크합니다.
      </Typography>

      {/* 전략 추가 */}
      <Box sx={{ display: 'flex', flexDirection: { xs: 'column', sm: 'row' }, gap: 1, mb: 3 }}>
        <Autocomplete
          options={availableStrategies}
          getOptionLabel={(option) => option.name || ''}
          value={selectedStrategy}
          onChange={(_, newValue) => setSelectedStrategy(newValue)}
          renderInput={(params) => (
            <TextField
              {...params}
              label="전략 검색"
              placeholder="전략을 검색하세요..."
              size="small"
            />
          )}
          renderOption={(props, option) => (
            <li {...props}>
              <Typography variant="body2">{option.name}</Typography>
            </li>
          )}
          sx={{ flexGrow: 1, minWidth: { xs: '100%', sm: '200px' } }}
          noOptionsText="사용 가능한 전략이 없습니다"
        />
        <Button
          variant="contained"
          startIcon={<AddIcon />}
          onClick={handleAdd}
          disabled={!selectedStrategy}
          sx={{ minWidth: { xs: '100%', sm: 'auto' } }}
        >
          추가
        </Button>
      </Box>

      {/* 추가된 알림 전략 목록 */}
      <Box sx={{ flexGrow: 1, overflow: 'auto' }}>
        {alertStrategies.length === 0 ? (
          <Box
            sx={{
              p: 3,
              textAlign: 'center',
              border: '2px dashed',
              borderColor: 'divider',
              borderRadius: 1,
            }}
          >
            <Typography variant="body2" color="text.secondary">
              추가된 알림 조건이 없습니다.
              <br />
              전략을 검색하여 추가하세요.
            </Typography>
          </Box>
        ) : (
          <List dense>
            {alertStrategies.map((alertStrategy, index) => (
              <ListItem
                key={alertStrategy.id}
                sx={{
                  borderRadius: 1,
                  mb: 0.5,
                  backgroundColor: 'action.hover',
                }}
              >
                <Box sx={{ display: 'flex', alignItems: 'center', mr: 2 }}>
                  <CheckCircleIcon color="success" fontSize="small" />
                </Box>
                <ListItemText
                  primary={
                    <Typography variant="body2" fontWeight="medium">
                      {index + 1}. {alertStrategy.strategyRuleName || `전략 ID: ${alertStrategy.strategyRuleId}`}
                    </Typography>
                  }
                  secondary={
                    <Typography variant="caption" color="text.secondary">
                      추가됨: {new Date(alertStrategy.createdAt!).toLocaleString()}
                    </Typography>
                  }
                />
                <ListItemSecondaryAction>
                  <IconButton
                    onClick={() => handleShowDetail(alertStrategy.strategyRuleId!)}
                    color="info"
                    size="small"
                    title="상세보기"
                    sx={{ mr: 1 }}
                  >
                    <InfoIcon />
                  </IconButton>
                  <IconButton
                    edge="end"
                    onClick={() => handleDelete(alertStrategy.id!)}
                    color="error"
                    size="small"
                    title="삭제"
                  >
                    <DeleteIcon />
                  </IconButton>
                </ListItemSecondaryAction>
              </ListItem>
            ))}
          </List>
        )}

        {/* 통계 */}
        {alertStrategies.length > 0 && (
          <Box sx={{ mt: 2, p: 2, bgcolor: 'background.paper', borderRadius: 1 }}>
            <Typography variant="caption" color="text.secondary">
              총 {alertStrategies.length}개의 전략이 알림 조건으로 설정되어 있습니다.
            </Typography>
          </Box>
        )}
      </Box>

      {/* 전략 상세 정보 Dialog */}
      <Dialog
        open={detailDialogOpen}
        onClose={handleCloseDetail}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle
          sx={{
            bgcolor: 'primary.main',
            color: 'white',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            py: 2,
          }}
        >
          <Typography variant="h6" component="span">
            전략 상세 정보
          </Typography>
          <IconButton
            onClick={handleCloseDetail}
            size="small"
            sx={{
              color: 'white',
              '&:hover': {
                bgcolor: 'rgba(255, 255, 255, 0.1)',
              },
            }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent dividers>
          {detailLoading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
              <CircularProgress />
            </Box>
          ) : detailStrategy ? (
            <Box>
              {/* 기본 정보 */}
              <Paper sx={{ p: 2, mb: 2, bgcolor: 'background.default' }}>
                <Typography variant="h6" gutterBottom>
                  {detailStrategy.name}
                </Typography>
                <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                  {detailStrategy.description || '설명이 없습니다.'}
                </Typography>
                <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
                  <Chip
                    label={detailStrategy.signalType === 'BUY' ? '매수 신호' : '매도 신호'}
                    color={detailStrategy.signalType === 'BUY' ? 'success' : 'error'}
                    size="small"
                  />
                  <Chip
                    label={detailStrategy.enabled ? '활성화' : '비활성화'}
                    color={detailStrategy.enabled ? 'success' : 'default'}
                    size="small"
                  />
                  {detailStrategy.trendType && (
                    <Chip
                      label={`추세: ${detailStrategy.trendType}`}
                      size="small"
                      variant="outlined"
                    />
                  )}
                </Box>
              </Paper>

              {/* 매수 조건 그룹 */}
              {detailStrategy.buyConditionGroups && detailStrategy.buyConditionGroups.length > 0 && (
                <Box sx={{ mb: 2 }}>
                  <Typography variant="subtitle2" gutterBottom sx={{ fontWeight: 'bold', color: 'success.main' }}>
                    매수 조건 그룹
                  </Typography>
                  {detailStrategy.buyConditionGroups.map((group, groupIndex) => (
                    <Paper key={groupIndex} sx={{ p: 2, mb: 1, bgcolor: 'background.default' }}>
                      <Typography variant="body2" fontWeight="medium" gutterBottom>
                        그룹 {groupIndex + 1} ({group.logicalOperator || 'AND'})
                      </Typography>
                      {group.conditions && group.conditions.length > 0 ? (
                        <Box sx={{ pl: 2 }}>
                          {group.conditions.map((condition, condIndex) => (
                            <Box key={condIndex} sx={{ mb: 0.5 }}>
                              <Typography variant="body2">
                                • {condition.indicatorType}
                                {condition.period && ` (${condition.period})`}
                                {' '}{condition.conditionType}
                                {condition.targetValue !== null && condition.targetValue !== undefined && ` ${condition.targetValue}`}
                                {condition.secondaryValue !== null && condition.secondaryValue !== undefined && ` ~ ${condition.secondaryValue}`}
                                {condition.description && (
                                  <Typography variant="caption" color="text.secondary" sx={{ ml: 1 }}>
                                    ({condition.description})
                                  </Typography>
                                )}
                              </Typography>
                            </Box>
                          ))}
                        </Box>
                      ) : (
                        <Typography variant="caption" color="text.secondary">
                          조건이 없습니다.
                        </Typography>
                      )}
                    </Paper>
                  ))}
                </Box>
              )}

              {/* 매도 조건 그룹 */}
              {detailStrategy.sellConditionGroups && detailStrategy.sellConditionGroups.length > 0 && (
                <Box>
                  <Typography variant="subtitle2" gutterBottom sx={{ fontWeight: 'bold', color: 'error.main' }}>
                    매도 조건 그룹
                  </Typography>
                  {detailStrategy.sellConditionGroups.map((group, groupIndex) => (
                    <Paper key={groupIndex} sx={{ p: 2, mb: 1, bgcolor: 'background.default' }}>
                      <Typography variant="body2" fontWeight="medium" gutterBottom>
                        그룹 {groupIndex + 1} ({group.logicalOperator || 'AND'})
                      </Typography>
                      {group.conditions && group.conditions.length > 0 ? (
                        <Box sx={{ pl: 2 }}>
                          {group.conditions.map((condition, condIndex) => (
                            <Box key={condIndex} sx={{ mb: 0.5 }}>
                              <Typography variant="body2">
                                • {condition.indicatorType}
                                {condition.period && ` (${condition.period})`}
                                {' '}{condition.conditionType}
                                {condition.targetValue !== null && condition.targetValue !== undefined && ` ${condition.targetValue}`}
                                {condition.secondaryValue !== null && condition.secondaryValue !== undefined && ` ~ ${condition.secondaryValue}`}
                                {condition.description && (
                                  <Typography variant="caption" color="text.secondary" sx={{ ml: 1 }}>
                                    ({condition.description})
                                  </Typography>
                                )}
                              </Typography>
                            </Box>
                          ))}
                        </Box>
                      ) : (
                        <Typography variant="caption" color="text.secondary">
                          조건이 없습니다.
                        </Typography>
                      )}
                    </Paper>
                  ))}
                </Box>
              )}

              {/* 추가 정보 */}
              <Divider sx={{ my: 2 }} />
              <Box>
                <Typography variant="caption" color="text.secondary" display="block">
                  생성일: {detailStrategy.createdAt ? new Date(detailStrategy.createdAt).toLocaleString() : '-'}
                </Typography>
                <Typography variant="caption" color="text.secondary" display="block">
                  수정일: {detailStrategy.updatedAt ? new Date(detailStrategy.updatedAt).toLocaleString() : '-'}
                </Typography>
              </Box>
            </Box>
          ) : (
            <Typography color="text.secondary">전략 정보를 불러올 수 없습니다.</Typography>
          )}
        </DialogContent>
      </Dialog>
    </Box>
  );
};

export default AlertStrategyPanel;
