import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  Button,
  Box,
  Typography,
  Grid,
  Paper,
  Chip,
  Divider,
  CircularProgress,
  Table,
  TableBody,
  TableCell,
  TableRow,
  Alert,
} from '@mui/material';
import {
  Close as CloseIcon,
  TrendingUp as TrendingUpIcon,
  TrendingDown as TrendingDownIcon,
  ShowChart as ShowChartIcon,
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { getNotificationDetail, AlertNotificationDetailDto, markAsRead } from '../../services/alertApi';
import { format } from 'date-fns';

interface AlertDetailDialogProps {
  open: boolean;
  notificationId: number | null;
  onClose: () => void;
  onMarkAsRead?: () => void;
}

/**
 * 알림 상세보기 다이얼로그
 */
const AlertDetailDialog: React.FC<AlertDetailDialogProps> = ({
  open,
  notificationId,
  onClose,
  onMarkAsRead,
}) => {
  const navigate = useNavigate();
  const [detail, setDetail] = useState<AlertNotificationDetailDto | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (open && notificationId) {
      loadDetail();
    }
  }, [open, notificationId]);

  const loadDetail = async () => {
    if (!notificationId) return;

    try {
      setLoading(true);
      setError(null);
      const data = await getNotificationDetail(notificationId);
      setDetail(data);

      // 읽음 처리
      if (!data.isRead) {
        await markAsRead(notificationId);
        if (onMarkAsRead) {
          onMarkAsRead();
        }
      }
    } catch (err: any) {
      console.error('알림 상세 정보 로드 실패:', err);
      setError('알림 상세 정보를 불러오는데 실패했습니다.');
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    setDetail(null);
    setError(null);
    onClose();
  };

  const handleShowChart = () => {
    if (detail?.symbol) {
      // 차트 분석 화면으로 이동하면서 종목 정보 전달
      navigate('/candlestick-test', { 
        state: { 
          symbol: detail.symbol,
          koreanName: detail.koreanName,
          englishName: detail.englishName
        } 
      });
      handleClose();
    }
  };

  const formatNumber = (value?: number, decimals: number = 2) => {
    if (value === undefined || value === null) return '-';
    return value.toFixed(decimals);
  };

  const formatPrice = (value?: number) => {
    if (value === undefined || value === null) return '-';
    return value.toLocaleString('ko-KR');
  };

  const formatPercent = (value?: number) => {
    if (value === undefined || value === null) return '-';
    const sign = value >= 0 ? '+' : '';
    return `${sign}${(value * 100).toFixed(2)}%`;
  };

  /** 시간봉 문자열을 한글 라벨로 변환 (1m→1분봉, 1h→1시간봉 등) */
  const getTimeIntervalLabel = (timeInterval?: string) => {
    if (!timeInterval) return '1시간봉';
    const unit = timeInterval.replace(/[^0-9]/g, '');
    const type = timeInterval.replace(/[0-9]/g, '').toLowerCase();
    const num = unit ? parseInt(unit, 10) : 1;
    if (type === 'm') return `${num}분봉`;
    if (type === 'h') return `${num}시간봉`;
    if (type === 'd') return '일봉';
    if (type === 'w') return '주봉';
    return '1시간봉';
  };

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth="md"
      fullWidth
      PaperProps={{
        sx: {
          minHeight: '60vh',
        },
      }}
    >
      <DialogTitle
        sx={{
          bgcolor: 'primary.main',
          color: 'white',
          py: 2,
        }}
      >
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <Typography variant="h6" sx={{ color: 'white' }}>
            알림 상세 정보 {detail && `- ${detail.koreanName || detail.symbol}`}
          </Typography>
          <Box sx={{ display: 'flex', gap: 1 }}>
            {detail?.symbol && (
              <Button 
                onClick={handleShowChart} 
                startIcon={<ShowChartIcon />}
                variant="contained"
                color="inherit"
                sx={{ 
                  bgcolor: 'white',
                  color: 'primary.main',
                  '&:hover': {
                    bgcolor: 'grey.100',
                  }
                }}
                size="small"
              >
                차트보기
              </Button>
            )}
            <Button 
              onClick={handleClose} 
              variant="contained"
              color="inherit"
              sx={{ 
                bgcolor: 'white',
                color: 'primary.main',
                '&:hover': {
                  bgcolor: 'grey.100',
                }
              }}
              size="small"
            >
              확인
            </Button>
            <Button 
              onClick={handleClose} 
              startIcon={<CloseIcon />} 
              variant="outlined"
              sx={{
                borderColor: 'white',
                color: 'white',
                '&:hover': {
                  borderColor: 'white',
                  bgcolor: 'rgba(255, 255, 255, 0.1)',
                }
              }}
              size="small"
            >
              닫기
            </Button>
          </Box>
        </Box>
      </DialogTitle>

      <DialogContent dividers>
        {loading && (
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: 300 }}>
            <CircularProgress />
          </Box>
        )}

        {error && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {error}
          </Alert>
        )}

        {!loading && !error && detail && (
          <Box>
            {/* 기본 정보 */}
            <Paper elevation={0} sx={{ p: 2, mb: 2, bgcolor: 'background.default' }}>
              <Grid container spacing={2}>
                <Grid item xs={12}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 1 }}>
                    <Typography variant="h5" fontWeight="bold">
                      {detail.koreanName || detail.symbol}
                    </Typography>
                    <Chip
                      label={detail.symbol}
                      size="small"
                      variant="outlined"
                    />
                    {detail.isRead ? (
                      <Chip label="읽음" size="small" color="default" />
                    ) : (
                      <Chip label="새 알림" size="small" color="primary" />
                    )}
                  </Box>
                  <Typography variant="body2" color="text.secondary">
                    {detail.englishName}
                  </Typography>
                </Grid>

                <Grid item xs={12}>
                  <Divider sx={{ my: 1 }} />
                </Grid>

                <Grid item xs={12} md={6}>
                  <Typography variant="caption" color="text.secondary">
                    알림 발생 시각
                  </Typography>
                  <Typography variant="body1">
                    {detail.triggeredAt
                      ? format(new Date(detail.triggeredAt), 'yyyy-MM-dd HH:mm:ss')
                      : '-'}
                  </Typography>
                </Grid>

                <Grid item xs={12} md={6}>
                  <Typography variant="caption" color="text.secondary">
                    알림 전송 시각
                  </Typography>
                  <Typography variant="body1">
                    {detail.notifiedAt
                      ? format(new Date(detail.notifiedAt), 'yyyy-MM-dd HH:mm:ss')
                      : '-'}
                  </Typography>
                </Grid>

                <Grid item xs={12}>
                  <Typography variant="caption" color="text.secondary">
                    알림 메시지
                  </Typography>
                  <Alert severity="success" sx={{ mt: 0.5 }}>
                    <Typography 
                      variant="body1" 
                      sx={{ 
                        whiteSpace: 'pre-line',
                        '& > div': { mt: 1 }
                      }}
                    >
                      {detail.message}
                    </Typography>
                  </Alert>
                </Grid>

                {detail.conditionDescription && (
                  <Grid item xs={12}>
                    <Typography variant="caption" color="text.secondary">
                      충족 조건
                    </Typography>
                    <Typography variant="body2" sx={{ mt: 0.5, whiteSpace: 'pre-line' }}>
                      {detail.conditionDescription}
                    </Typography>
                  </Grid>
                )}
              </Grid>
            </Paper>

            {/* 현재 시세 정보 */}
            {detail.currentPrice && (
              <Paper elevation={0} sx={{ p: 2, mb: 2 }}>
                <Typography variant="h6" gutterBottom>
                  현재 시세 ({getTimeIntervalLabel(detail.timeInterval)} 기준)
                </Typography>
                <Grid container spacing={2}>
                  <Grid item xs={6} md={4}>
                    <Typography variant="caption" color="text.secondary">
                      현재가
                    </Typography>
                    <Typography variant="h6">{formatPrice(detail.currentPrice)} 원</Typography>
                  </Grid>
                  <Grid item xs={6} md={4}>
                    <Typography variant="caption" color="text.secondary">
                      변화율
                    </Typography>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                      {detail.changeRate && detail.changeRate >= 0 ? (
                        <TrendingUpIcon color="error" fontSize="small" />
                      ) : (
                        <TrendingDownIcon color="primary" fontSize="small" />
                      )}
                      <Typography
                        variant="h6"
                        color={detail.changeRate && detail.changeRate >= 0 ? 'error' : 'primary'}
                      >
                        {formatPercent(detail.changeRate)}
                      </Typography>
                    </Box>
                  </Grid>
                  <Grid item xs={12} md={4}>
                    <Typography variant="caption" color="text.secondary">
                      거래량
                    </Typography>
                    <Typography variant="body1">{formatPrice(detail.volume)}</Typography>
                  </Grid>
                </Grid>
              </Paper>
            )}

            {/* 기술적 지표 */}
            {detail.indicatorData && (
              <Paper elevation={0} sx={{ p: 2, mb: 2 }}>
                <Typography variant="h6" gutterBottom>
                  기술적 지표 ({getTimeIntervalLabel(detail.timeInterval)} 기준)
                </Typography>
                <Table size="small">
                  <TableBody>
                    {detail.indicatorData.rsi !== undefined && (
                      <TableRow>
                        <TableCell><strong>RSI</strong></TableCell>
                        <TableCell align="right">{formatNumber(detail.indicatorData.rsi)}</TableCell>
                        <TableCell>
                          {detail.indicatorData.rsi > 70 ? (
                            <Chip label="과매수" size="small" color="error" />
                          ) : detail.indicatorData.rsi < 30 ? (
                            <Chip label="과매도" size="small" color="primary" />
                          ) : (
                            <Chip label="중립" size="small" color="default" />
                          )}
                        </TableCell>
                      </TableRow>
                    )}
                    {detail.indicatorData.macdLine !== undefined && (
                      <>
                        <TableRow>
                          <TableCell><strong>MACD</strong></TableCell>
                          <TableCell align="right">{formatNumber(detail.indicatorData.macdLine)}</TableCell>
                          <TableCell></TableCell>
                        </TableRow>
                        {detail.indicatorData.signalLine !== undefined && (
                          <TableRow>
                            <TableCell><strong>Signal</strong></TableCell>
                            <TableCell align="right">{formatNumber(detail.indicatorData.signalLine)}</TableCell>
                            <TableCell></TableCell>
                          </TableRow>
                        )}
                        {detail.indicatorData.histogram !== undefined && (
                          <TableRow>
                            <TableCell><strong>Histogram</strong></TableCell>
                            <TableCell align="right">{formatNumber(detail.indicatorData.histogram)}</TableCell>
                            <TableCell>
                              {detail.indicatorData.histogram > 0 ? (
                                <Chip label="상승" size="small" color="error" />
                              ) : (
                                <Chip label="하락" size="small" color="primary" />
                              )}
                            </TableCell>
                          </TableRow>
                        )}
                      </>
                    )}
                    {detail.indicatorData.stochK !== undefined && (
                      <TableRow>
                        <TableCell><strong>Stochastic K</strong></TableCell>
                        <TableCell align="right">{formatNumber(detail.indicatorData.stochK)}</TableCell>
                        <TableCell></TableCell>
                      </TableRow>
                    )}
                    {detail.indicatorData.stochD !== undefined && (
                      <TableRow>
                        <TableCell><strong>Stochastic D</strong></TableCell>
                        <TableCell align="right">{formatNumber(detail.indicatorData.stochD)}</TableCell>
                        <TableCell></TableCell>
                      </TableRow>
                    )}
                    {detail.indicatorData.cci !== undefined && (
                      <TableRow>
                        <TableCell><strong>CCI</strong></TableCell>
                        <TableCell align="right">{formatNumber(detail.indicatorData.cci)}</TableCell>
                        <TableCell></TableCell>
                      </TableRow>
                    )}
                    {detail.indicatorData.adx !== undefined && (
                      <TableRow>
                        <TableCell><strong>ADX</strong></TableCell>
                        <TableCell align="right">{formatNumber(detail.indicatorData.adx)}</TableCell>
                        <TableCell>
                          {detail.indicatorData.adx > 25 ? (
                            <Chip label="강한 추세" size="small" color="error" />
                          ) : (
                            <Chip label="약한 추세" size="small" color="default" />
                          )}
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </Paper>
            )}

            {/* 충족된 조건 목록 */}
            {detail.satisfiedConditions && detail.satisfiedConditions.length > 0 && (
              <Paper elevation={0} sx={{ p: 2 }}>
                <Typography variant="h6" gutterBottom>
                  충족된 조건 목록
                </Typography>
                {detail.satisfiedConditions.map((condition, index) => (
                  <Box key={index} sx={{ mb: 1 }}>
                    <Chip
                      label={`${condition.indicatorType} ${condition.conditionType}`}
                      size="small"
                      color="success"
                      sx={{ mr: 1 }}
                    />
                    {condition.description && (
                      <Typography variant="body2" component="span" color="text.secondary">
                        {condition.description}
                      </Typography>
                    )}
                  </Box>
                ))}
              </Paper>
            )}
          </Box>
        )}
      </DialogContent>
    </Dialog>
  );
};

export default AlertDetailDialog;
