import React, { useState, useEffect, useCallback } from 'react';
import {
  Box,
  Container,
  Paper,
  Typography,
  List,
  ListItem,
  ListItemText,
  IconButton,
  Divider,
  Button,
  Chip,
  Alert,
  CircularProgress,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
} from '@mui/material';
import {
  Delete as DeleteIcon,
  DeleteSweep as DeleteSweepIcon,
  Refresh as RefreshIcon,
  CheckCircle as CheckCircleIcon,
  Circle as CircleIcon,
  Info as InfoIcon,
} from '@mui/icons-material';
import { getNotifications, deleteNotification, deleteReadNotifications, markNotificationAsRead } from '../services/alertApi';
import type { AlertNotificationDto } from '../services/alertApi';
import AlertDetailDialog from '../components/alert/AlertDetailDialog';
import { useAlertNotification } from '../contexts/AlertNotificationContext';

/**
 * 알림 목록 페이지
 */
const NotificationListPage: React.FC = () => {
  const { latestNotification } = useAlertNotification();
  const [notifications, setNotifications] = useState<AlertNotificationDto[]>([]);
  const [loading, setLoading] = useState(true);
  const [initialFetchDone, setInitialFetchDone] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deleteAllDialogOpen, setDeleteAllDialogOpen] = useState(false);
  const [selectedNotificationId, setSelectedNotificationId] = useState<number | null>(null);
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);
  const [selectedDetailNotificationId, setSelectedDetailNotificationId] = useState<number | null>(null);

  const loadNotifications = useCallback(async (showSpinner = true) => {
    try {
      if (showSpinner) {
        setLoading(true);
        setError(null);
      }
      const response = await getNotifications();
      setNotifications(response.content || []);
    } catch (err) {
      console.error('알림 목록 로드 실패:', err);
      if (showSpinner) {
        setError('알림 목록을 불러오는데 실패했습니다.');
      }
    } finally {
      if (showSpinner) {
        setLoading(false);
      }
      setInitialFetchDone(true);
    }
  }, []);

  useEffect(() => {
    void loadNotifications(true);
  }, [loadNotifications]);

  /** 실시간 알림(SSE) 반영: 목록 상단에 추가 후 서버 목록과 맞춤 */
  useEffect(() => {
    if (!initialFetchDone || latestNotification?.id == null) return;
    setNotifications((prev) => {
      if (prev.some((n) => n.id === latestNotification.id)) return prev;
      return [latestNotification, ...prev];
    });
    void loadNotifications(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps -- id 변경 시에만 동기화
  }, [latestNotification?.id, initialFetchDone, loadNotifications]);

  const handleMarkAsRead = async (notificationId: number) => {
    try {
      await markNotificationAsRead(notificationId);
      setNotifications(prev =>
        prev.map(n => (n.id === notificationId ? { ...n, isRead: true } : n))
      );
    } catch (err) {
      console.error('알림 읽음 처리 실패:', err);
    }
  };

  const handleDeleteClick = (notificationId: number) => {
    setSelectedNotificationId(notificationId);
    setDeleteDialogOpen(true);
  };

  const handleDeleteConfirm = async () => {
    if (selectedNotificationId) {
      try {
        await deleteNotification(selectedNotificationId);
        setNotifications(prev => prev.filter(n => n.id !== selectedNotificationId));
        setDeleteDialogOpen(false);
        setSelectedNotificationId(null);
      } catch (err) {
        console.error('알림 삭제 실패:', err);
        alert('알림 삭제에 실패했습니다.');
      }
    }
  };

  const handleDeleteAllReadClick = () => {
    setDeleteAllDialogOpen(true);
  };

  const handleDeleteAllReadConfirm = async () => {
    try {
      await deleteReadNotifications();
      setNotifications(prev => prev.filter(n => !n.isRead));
      setDeleteAllDialogOpen(false);
    } catch (err) {
      console.error('읽은 알림 삭제 실패:', err);
      alert('읽은 알림 삭제에 실패했습니다.');
    }
  };

  const handleShowDetail = (notificationId: number) => {
    setSelectedDetailNotificationId(notificationId);
    setDetailDialogOpen(true);
  };

  const handleCloseDetail = () => {
    setDetailDialogOpen(false);
    setSelectedDetailNotificationId(null);
    void loadNotifications(true);
  };

  const handleDoubleClick = (notificationId: number) => {
    if (notificationId) {
      handleShowDetail(notificationId);
    }
  };

  const handleDetailButtonClick = (notificationId: number, event: React.MouseEvent) => {
    event.stopPropagation();
    if (notificationId) {
      handleShowDetail(notificationId);
    }
  };

  const formatDate = (dateString?: string) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const seconds = Math.floor(diff / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    if (days > 0) return `${days}일 전`;
    if (hours > 0) return `${hours}시간 전`;
    if (minutes > 0) return `${minutes}분 전`;
    return '방금 전';
  };

  const unreadCount = notifications.filter(n => !n.isRead).length;
  const readCount = notifications.filter(n => n.isRead).length;

  if (loading && notifications.length === 0) {
    return (
      <Container maxWidth="lg" sx={{ mt: 4, mb: 4, display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '60vh' }}>
        <CircularProgress />
      </Container>
    );
  }

  return (
    <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
      {/* Header */}
      <Box sx={{ mb: 4, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Box>
          <Typography variant="h4" component="h1" gutterBottom>
            알림 목록
          </Typography>
          <Box sx={{ display: 'flex', gap: 1, mt: 1 }}>
            <Chip
              label={`전체 ${notifications.length}개`}
              size="small"
              color="default"
            />
            <Chip
              label={`미읽음 ${unreadCount}개`}
              size="small"
              color="primary"
            />
            <Chip
              label={`읽음 ${readCount}개`}
              size="small"
              color="success"
            />
          </Box>
        </Box>
        <Box sx={{ display: 'flex', gap: 1 }}>
          <Button
            variant="outlined"
            startIcon={<RefreshIcon />}
            onClick={() => void loadNotifications(true)}
          >
            새로고침
          </Button>
          {readCount > 0 && (
            <Button
              variant="outlined"
              color="error"
              startIcon={<DeleteSweepIcon />}
              onClick={handleDeleteAllReadClick}
            >
              읽은 알림 모두 삭제
            </Button>
          )}
        </Box>
      </Box>

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

      {/* Notification List */}
      <Paper sx={{ p: 0 }}>
        {notifications.length === 0 ? (
          <Box sx={{ p: 4, textAlign: 'center' }}>
            <Typography variant="body1" color="text.secondary">
              알림이 없습니다.
            </Typography>
          </Box>
        ) : (
          <List sx={{ p: 0 }}>
            {notifications.map((notification, index) => (
              <React.Fragment key={notification.id}>
                <ListItem
                  onDoubleClick={() => notification.id && handleDoubleClick(notification.id)}
                  sx={{
                    py: 2,
                    px: 3,
                    backgroundColor: notification.isRead ? 'transparent' : 'action.hover',
                    '&:hover': {
                      backgroundColor: notification.isRead ? 'action.hover' : 'action.selected',
                    },
                    cursor: 'pointer',
                  }}
                  secondaryAction={
                    <Box sx={{ display: 'flex', gap: 1 }}>
                      <IconButton
                        edge="end"
                        onClick={(e) => notification.id && handleDetailButtonClick(notification.id, e)}
                        title="상세보기"
                        color="primary"
                        size="small"
                      >
                        <InfoIcon />
                      </IconButton>
                      <IconButton
                        edge="end"
                        aria-label="delete"
                        onClick={() => handleDeleteClick(notification.id!)}
                        title="삭제"
                        color="error"
                        size="small"
                      >
                        <DeleteIcon />
                      </IconButton>
                    </Box>
                  }
                >
                  <Box
                    sx={{
                      mr: 2,
                      display: 'flex',
                      alignItems: 'center',
                      cursor: notification.isRead ? 'default' : 'pointer',
                    }}
                    onClick={() => !notification.isRead && handleMarkAsRead(notification.id!)}
                  >
                    {notification.isRead ? (
                      <CheckCircleIcon color="success" fontSize="small" />
                    ) : (
                      <CircleIcon color="primary" fontSize="small" />
                    )}
                  </Box>
                  <ListItemText
                    primary={
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
                        <Typography
                          variant="subtitle1"
                          sx={{ fontWeight: notification.isRead ? 'normal' : 'bold' }}
                        >
                          {notification.koreanName || notification.symbol}
                        </Typography>
                        <Chip
                          label={formatDate(notification.triggeredAt)}
                          size="small"
                          variant="outlined"
                        />
                      </Box>
                    }
                    secondary={
                      <>
                        <Typography
                          component="span"
                          variant="body2"
                          color="text.primary"
                          sx={{ display: 'block', mb: 0.5 }}
                        >
                          {notification.message}
                        </Typography>
                        {notification.conditionDescription && (
                          <Typography
                            component="span"
                            variant="caption"
                            color="text.secondary"
                          >
                            {notification.conditionDescription}
                          </Typography>
                        )}
                      </>
                    }
                  />
                </ListItem>
                {index < notifications.length - 1 && <Divider />}
              </React.Fragment>
            ))}
          </List>
        )}
      </Paper>

      {/* Delete Confirmation Dialog */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>알림 삭제</DialogTitle>
        <DialogContent>
          <DialogContentText>
            이 알림을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>취소</Button>
          <Button onClick={handleDeleteConfirm} color="error" autoFocus>
            삭제
          </Button>
        </DialogActions>
      </Dialog>

      {/* Delete All Read Confirmation Dialog */}
      <Dialog
        open={deleteAllDialogOpen}
        onClose={() => setDeleteAllDialogOpen(false)}
      >
        <DialogTitle>읽은 알림 모두 삭제</DialogTitle>
        <DialogContent>
          <DialogContentText>
            읽은 알림 {readCount}개를 모두 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteAllDialogOpen(false)}>취소</Button>
          <Button onClick={handleDeleteAllReadConfirm} color="error" autoFocus>
            모두 삭제
          </Button>
        </DialogActions>
      </Dialog>

      {/* 알림 상세 다이얼로그 */}
      <AlertDetailDialog
        open={detailDialogOpen}
        notificationId={selectedDetailNotificationId}
        onClose={handleCloseDetail}
        onMarkAsRead={() => void loadNotifications(true)}
      />
    </Container>
  );
};

export default NotificationListPage;

