import { useEffect, useState } from "react";
import { styled } from "@mui/material/styles";
import {
  Dialog,
  DialogContent,
  DialogTitle,
  Checkbox,
  FormControlLabel,
  Button,
  Paper,
  Typography,
} from "@mui/material";
import { useTranslation } from "react-i18next";
import { useAppDispatch, useAppSelector } from "../../redux/hooks.ts";
import { getAnnouncement } from "../../redux/thunks/site.ts";
import SessionManager from "../../session";

interface AnnouncementDialogProps {
  forceOpen?: boolean;
  onClose?: () => void;
}

// 为公告内容创建一个带样式的容器组件
const AnnouncementContent = styled("div")`
  h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    margin-top: 16px;
    margin-bottom: 8px;
  }
  p {
    margin-bottom: 12px;
    line-height: 1.6;
  }
  ul,
  ol {
    margin-left: 24px;
    margin-bottom: 12px;
  }
  li {
    margin-bottom: 4px;
  }
  a {
    color: #1976d2;
    text-decoration: none;
    &:hover {
      text-decoration: underline;
    }
  }
  img {
    max-width: 100%;
    height: auto;
  }
  table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 16px;
  }
  th,
  td {
    border: 1px solid #e0e0e0;
    padding: 8px;
  }
  th {
    background-color: #f5f5f5;
  }
`;

const AnnouncementDialog = ({ forceOpen = false, onClose }: AnnouncementDialogProps) => {
  const { t } = useTranslation("common");
  const dispatch = useAppDispatch();
  const announcement = useAppSelector((state) => state.siteConfig.basic.config.announcement || "");
  const announcementEnabled = useAppSelector((state) => state.siteConfig.basic.config.announcement_enabled || false);
  const [open, setOpen] = useState(false);
  const [dontShowAgain, setDontShowAgain] = useState(false);

  useEffect(() => {
    // 加载公告
    dispatch(getAnnouncement());
  }, [dispatch]);

  // 保存上次显示的公告内容，用于检测公告是否更新
  const [lastAnnouncement, setLastAnnouncement] = useState("");

  useEffect(() => {
    // 检查公告是否更新
    const hasAnnouncementChanged = announcement !== lastAnnouncement && lastAnnouncement !== "";

    // 如果公告已更新，清除不再显示状态并强制显示
    if (hasAnnouncementChanged) {
      // 使用特殊标记来覆盖之前的设置
      SessionManager.set("announcement_dismissed", "false");
    }

    // 更新上次显示的公告内容
    if (announcement) {
      setLastAnnouncement(announcement);
    }

    // 检查是否应该显示公告
    // 更健壮的检测逻辑：只有当设置为"true"时才视为不再显示
    const dismissed = SessionManager.get("announcement_dismissed") === "true";
    const shouldShow = announcementEnabled && announcement && announcement.trim() !== "" && !dismissed;

    if (shouldShow) {
      // 延迟显示，让页面加载完成
      const timer = setTimeout(() => setOpen(true), 1000);
      return () => clearTimeout(timer);
    } else {
      // 确保当不应该显示且没有强制打开时关闭弹窗
      if (!forceOpen) {
        setOpen(false);
      }
    }
  }, [announcement, announcementEnabled, lastAnnouncement]);

  // 处理外部强制打开
  useEffect(() => {
    if (forceOpen && announcement && announcement.trim() !== "") {
      setOpen(true);
      // 重置不再显示选项
      setDontShowAgain(false);
    }
  }, [announcement, announcementEnabled, lastAnnouncement, forceOpen]);

  const handleClose = () => {
    if (dontShowAgain) {
      // 保存用户选择不再显示
      SessionManager.set("announcement_dismissed", "true");
    }
    setOpen(false);
    // 通知父组件弹窗已关闭
    if (onClose) {
      onClose();
    }
  };

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="md" fullWidth>
      <DialogTitle sx={{ borderBottom: 1, borderColor: "divider", paddingBottom: 1 }}>
        {t("announcement", "公告")}
      </DialogTitle>
      <DialogContent sx={{ padding: 2, maxHeight: "80vh" }}>
        <Paper elevation={0} sx={{ p: 2 }}>
          <AnnouncementContent dangerouslySetInnerHTML={{ __html: announcement }} />
        </Paper>
        <FormControlLabel
          control={<Checkbox checked={dontShowAgain} onChange={(e) => setDontShowAgain(e.target.checked)} />}
          label={t("dontShowAgain", "不再显示")}
          sx={{ mt: 2 }}
        />
      </DialogContent>
      <Button onClick={handleClose} variant="contained" color="primary" sx={{ m: 2 }}>
        {t("ok", "确定")}
      </Button>
    </Dialog>
  );
};

// 导出一个可以被外部组件控制的版本
export { AnnouncementDialog };
export default AnnouncementDialog;
