import { Typography, Avatar, Badge, Chip, Box, Button } from "@mui/material";
import { Tooltip as MUITooltip } from "@mui/material";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import {
  Chart as ChartJs,
  ArcElement,
  Tooltip,
  Legend,
  BarElement,
  CategoryScale,
  LinearScale,
  LineElement,
  PointElement,
} from "chart.js";
import ChartDataLabels from "chartjs-plugin-datalabels";
import { PieChartSection } from "../dashboard-pie-chart-section/PieChartSection";
import { InventorySection } from "../dashboard-inventory-section/InventorySection";
import { WarehouseInfoSection } from "../dashboard-ware-house-info-section/WarehouseInfoSection";
import { PriceChartSection } from "../dashboard-price-chart-section/PriceChartSection";
import AnnouncementIcon from "@mui/icons-material/Announcement";
import { getUnseenMessages } from "../../../authentication/services/getUnseenMessage";
import { motion } from "framer-motion";
import CircleNotificationsIcon from "@mui/icons-material/CircleNotifications";
import { useNavigate } from "react-router-dom";
import { YesterdayKillingReport } from "../dashboard-yesterday-killing-report/YesterdayKillingReport";
import { BarChartSection } from "../dashboard-bar-chart-section/BarChartSection";
import { DailykillingReport } from "../dashboard-daily-killing-report/DailyKillingReport ";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { StatBox } from "../dashboard-state-box/StatBox";
import { dashboardGetMonitoringService } from "../../services/dashboard-get-service";
import { dashboardGetTicketService } from "../../services/dashboard-ticket-service";
import { dashboardGetNewsService } from "../../services/dashboard-get-news-service";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import axios from "axios";
import { RiFileExcel2Fill } from "react-icons/ri";

ChartJs.register(
  ArcElement,
  Tooltip,
  Legend,
  ChartDataLabels,
  BarElement,
  CategoryScale,
  LinearScale,
  LineElement,
  PointElement
);

export const Dashboard = () => {
  const dispatch = useDispatch();

  const [boxStats, setBoxStats] = useState({
    hatching: {},
    yesterdayKilling: {},
    Killing: {},
    inventory: {},
    warehouseKillHouse: {},
    warehouseInformation: {},
    chickenPrice: [],
  });

  const [notifications, setNotifications] = useState([]);
  const [tickets, setTickets] = useState([]);
  const [unseenMessages, setUnseenMessages] = useState({
    state: false,
    num: 0,
  });
  const navigate = useNavigate();

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(dashboardGetMonitoringService()).then((r) => {
      if (r.payload?.data) {
        setBoxStats(r.payload.data);
      }
      dispatch(LOADING_END());
    });
  }, [dispatch]);

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(dashboardGetNewsService()).then((r) => {
      if (r.payload?.data) {
        const formattedNotifications = r.payload.data.map((item) => ({
          id: item.id,
          title: item.title,
          date: item.created_at,
          type: item.status || "تازه",
          message: item.text,
          isNew: true,
        }));
        setNotifications(formattedNotifications);
      } else {
        setNotifications([]);
      }
      dispatch(LOADING_END());
    });
  }, [dispatch]);

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(dashboardGetTicketService()).then((r) => {
      if (r.payload?.data) {
        const ticketsData = Array.isArray(r.payload.data)
          ? r.payload.data
          : [r.payload.data];
        setTickets(ticketsData);
      } else {
        setTickets([]);
      }
      dispatch(LOADING_END());
    });
  }, [dispatch]);

  useEffect(() => {
    dispatch(getUnseenMessages()).then((r) => {
      setUnseenMessages(r.payload.data);
    });
  }, [window.location.pathname]);

  const handleNotificationClick = (id) => {
    navigate(`/ticket/${id}/false`);
  };

  const statBoxes = [
    {
      title: "حجم جوجه ریزی فعال (قطعه)",
      value: boxStats?.hatching?.quantity || 0,
    },
    {
      title: "حجم کشتار شده (قطعه)",
      value: boxStats?.hatching?.killedQuantity || 0,
    },
    {
      title: "حجم مانده در سالن (قطعه)",
      value: boxStats?.hatching?.leftOver || 0,
    },
    {
      title: "حجم مانده در سالن بزرگتر از 40 روز(قطعه) ",
      value: boxStats?.hatching?.leftOverBetweenFortySeventyFive || 0,
    },
    {
      title: "میانگین سن کشتار فارم های فعال",
      value: boxStats?.hatching?.killingAveAge || 0,
    },
  ];

  return (
    <Grid
      container
      alignItems="center"
      justifyContent="flex-start"
      gap={SPACING.SMALL}
      sx={{ padding: SPACING.SMALL }}
    >
      <Box sx={{ width: "100%", mb: 2 }}>
        <Box
          sx={{
            display: "flex",
            flexDirection: { xs: "column", md: "row" },
            gap: 2,
            width: "100%",
            mb: 2,
          }}
        >
          <Box
            sx={{
              width: { xs: "100%", md: "60%" },
              border: "1px solid",
              borderColor: "divider",
              borderRadius: "16px",
              overflow: "hidden",
              height: 250,
              display: "flex",
              flexDirection: "column",
            }}
          >
            <Box
              sx={{
                display: "flex",
                alignItems: "center",
                gap: 1,
                color: "white",
                p: 2,
                backgroundColor: "#00cc99",
              }}
            >
              <AnnouncementIcon />
              <Typography variant="body1" fontWeight="bold" textAlign="left">
                آخرین اطلاعیه و اخبار
              </Typography>
            </Box>

            {notifications.length > 0 ? (
              <Box
                sx={{
                  p: 2,
                  overflowY: "auto",
                  flexGrow: 1,
                  scrollBehavior: "smooth",
                  scrollbarWidth: "thin",
                  "&::-webkit-scrollbar": { width: "6px" },
                  "&::-webkit-scrollbar-thumb": {
                    backgroundColor: "#ccc",
                    borderRadius: "8px",
                  },
                  "&:hover::-webkit-scrollbar-thumb": {
                    backgroundColor: "#999",
                  },
                }}
              >
                {notifications.map((notification) => (
                  <Box
                    key={notification.id}
                    sx={{
                      mb: 2,
                      p: 1,
                      borderRadius: 1,
                      bgcolor: notification.isNew
                        ? "action.selected"
                        : "background.paper",
                      boxShadow: 1,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "space-between",
                      gap: 2,
                    }}
                  >
                    <Box>
                      <Typography variant="body1" textAlign="left">
                        {notification.title}
                      </Typography>
                      <Typography
                        variant="caption"
                        textAlign="left"
                        sx={{
                          textAlign: "left",
                        }}
                      >
                        {notification.message}
                      </Typography>
                    </Box>
                    <Box>
                      <Typography variant="body1" textAlign="left">
                        {notification.date}
                      </Typography>
                    </Box>

                    <Chip
                      label={notification.type}
                      size="medium"
                      sx={{
                        bgcolor:
                          notification.type === "فوری"
                            ? "#B0E4DD"
                            : notification.type === "داغ ترین"
                            ? "#FFCFCF"
                            : "#D0DCFF",
                        color:
                          notification.type === "فوری"
                            ? "#004736"
                            : notification.type === "داغ ترین"
                            ? "#EB5757"
                            : "#2D5FFF",
                        minWidth: 80,
                        textAlign: "center",
                      }}
                    />
                  </Box>
                ))}
              </Box>
            ) : (
              <Box
                sx={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  flexGrow: 1,
                }}
              >
                <Typography variant="body1" color="text.secondary">
                  اخبار جدیدی وجود ندارد
                </Typography>
              </Box>
            )}
          </Box>

          <Box
            sx={{
              width: { xs: "100%", md: "40%" },
              border: "1px solid",
              borderColor: "divider",
              borderRadius: "16px",
              overflow: "hidden",
              height: 250,
              display: "flex",
              flexDirection: "column",
            }}
          >
            <Box
              sx={{
                display: "flex",
                alignItems: "center",
                gap: 1,
                color: "white",
                p: 2,
                backgroundColor: "primary.main",
              }}
            >
              <AnnouncementIcon />
              <Typography variant="body1" fontWeight="bold" textAlign="left">
                تیکت های خوانده نشده
              </Typography>
              {unseenMessages?.state ? (
                <motion.div
                  initial={{ y: 0 }}
                  animate={{ y: [0, -2, 0] }}
                  transition={{
                    duration: 0.5,
                    repeat: Infinity,
                    repeatType: "loop",
                  }}
                >
                  <Badge
                    badgeContent={unseenMessages?.num}
                    color="error"
                    anchorOrigin={{
                      vertical: "top",
                      horizontal: "left",
                    }}
                  >
                    <CircleNotificationsIcon />
                  </Badge>
                </motion.div>
              ) : (
                <CircleNotificationsIcon />
              )}
            </Box>

            {tickets.length > 0 ? (
              <Box
                sx={{
                  p: 2,
                  overflowY: "auto",
                  flexGrow: 1,
                  scrollBehavior: "smooth",
                  scrollbarWidth: "thin",
                  "&::-webkit-scrollbar": {
                    width: "6px",
                  },
                  "&::-webkit-scrollbar-thumb": {
                    backgroundColor: "#ccc",
                    borderRadius: "8px",
                  },
                  "&:hover::-webkit-scrollbar-thumb": {
                    backgroundColor: "#999",
                  },
                }}
              >
                {tickets.map((ticket) => (
                  <Box
                    key={ticket.id}
                    sx={{
                      mb: 2,
                      p: 2,
                      borderRadius: 1,
                      bgcolor: ticket.unread_message
                        ? "action.selected"
                        : "background.paper",
                      boxShadow: 1,
                    }}
                  >
                    <Box
                      sx={{
                        display: "flex",
                        alignItems: "center",
                        mb: 1,
                        cursor: "pointer",
                      }}
                      onClick={() => {
                        handleNotificationClick(ticket?.ticketId);
                      }}
                    >
                      <Avatar
                        sx={{
                          bgcolor: "primary.main",
                          color: "white",
                          width: 24,
                          height: 24,
                          mr: 1,
                        }}
                      >
                        {ticket.user?.fullname?.charAt(0) || ""}
                      </Avatar>
                      <Typography variant="subtitle2" fontWeight="bold">
                        {ticket.user?.fullname || "نامشخص"}
                      </Typography>
                      {ticket.unread_message && (
                        <Chip
                          label="جدید"
                          size="small"
                          color="error"
                          sx={{ ml: "auto" }}
                        />
                      )}
                    </Box>
                    <Typography
                      variant="body2"
                      color="text.secondary"
                      textAlign="left"
                    >
                      {ticket.title}
                    </Typography>
                  </Box>
                ))}
              </Box>
            ) : (
              <Box
                sx={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  flexGrow: 1,
                }}
              >
                <Typography variant="body1" color="primary.main">
                  تیکتی جهت نمایش وجود ندارد
                </Typography>
              </Box>
            )}
          </Box>
        </Box>
      </Box>

      <Grid
        container
        sx={{
          width: "100%",
          borderRadius: "16px",
          border: "1px solid",
          borderColor: "divider",
          p: 2,
          overflow: "hidden",
        }}
      >
        <Typography
          variant="subtitle1"
          sx={{
            width: "100%",
            textAlign: "start",
            fontWeight: "600",
            mb: 2,
            px: 1,
            fontSize: "1rem",
          }}
          color="text.primary"
        >
          آمار جوجه ریزی استان
        </Typography>

        <Grid
          container
          // spacing={2}
          sx={{
            width: "100%",
            margin: 0,
          }}
        >
          {statBoxes.map((box, index) => (
            <Grid
              item
              key={index}
              xs={12}
              sm={6}
              md={4}
              lg={2.4}
              sx={{
                display: "flex",
                justifyContent: "center",
                minHeight: "20%",
                pb: { xs: 1, lg: 2 },
              }}
            >
              <StatBox
                title={box.title}
                value={box.value}
                color={index % 2 === 0 ? "primary" : "secondary"}
              />
            </Grid>
          ))}
        </Grid>
      </Grid>
      <Grid item xs={12} my={SPACING.MEDIUM}>
        <ResponsiveTable
          isDashboard
          noPagination
          operation={
            <MUITooltip title="خروجی اکسل">
              <a
                href={`${axios.defaults.baseURL}hatching_for_every_age_range/`}
                rel="noreferrer"
              >
                <Button color="success">
                  <RiFileExcel2Fill size={24} />
                </Button>
              </a>
            </MUITooltip>
          }
          data={[
            [
              boxStats?.hatching?.totalLeftOverLt35?.toLocaleString() || "0",
              boxStats?.hatching?.totalLeftOverBetween3540?.toLocaleString() ||
                "0",
              boxStats?.hatching?.totalLeftOverBetween4045?.toLocaleString() ||
                "0",
              boxStats?.hatching?.totalLeftOverBetween4550?.toLocaleString() ||
                "0",
              boxStats?.hatching?.totalLeftOverBetween5055?.toLocaleString() ||
                "0",
              boxStats?.hatching?.totalLeftOverBetween5560?.toLocaleString() ||
                "0",
              boxStats?.hatching?.totalLeftOverBetween6065?.toLocaleString() ||
                "0",
              boxStats?.hatching?.totalLeftOverBetween6570?.toLocaleString() ||
                "0",
              boxStats?.hatching?.totalLeftOverGt70?.toLocaleString() || "0",
            ],
          ]}
          allColors={{ color: "#244CCC", text: "#fff" }}
          columns={[
            "کمتر از 35 روز",
            "بین 35 تا 40 روز",
            "بین 40 تا 45 روز",
            "بین 45 تا 50 روز",
            "بین 50 تا 55 روز",
            "بین 55 تا 60 روز",
            "بین 60 تا 65 روز",
            "بین 65 تا 70 روز",
            "بیش از 70 روز",
          ]}
          title="مانده در سالن (قطعه)"
        />
      </Grid>
      <Grid container item xs={12} spacing={2} sx={{ alignItems: "stretch" }}>
        <Grid item xs={12} xl={4} sx={{ display: "flex" }}>
          <DailykillingReport boxStats={boxStats} />
        </Grid>
        <Grid item xs={12} xl={4}>
          <Box
            sx={{
              display: "flex",
              flexDirection: "column",
              gap: 2,
              height: "100%",
            }}
          >
            <WarehouseInfoSection boxStats={boxStats} sx={{ flex: 1 }} />
            <InventorySection boxStats={boxStats} sx={{ flex: 1 }} />
          </Box>
        </Grid>
        <Grid item xs={12} xl={4} sx={{ display: "flex" }}>
          <YesterdayKillingReport boxStats={boxStats} />
        </Grid>
      </Grid>
      <Grid
        container
        item
        xs={12}
        spacing={2}
        sx={{ mt: 2, alignItems: "stretch" }}
      >
        <Grid item xs={12} lg={4} sx={{ display: "flex" }}>
          <BarChartSection boxStats={boxStats} />
        </Grid>
        <Grid item xs={12} lg={4} sx={{ display: "flex" }}>
          <PieChartSection boxStats={boxStats} />
        </Grid>
        <Grid item xs={12} lg={4} sx={{ display: "flex" }}>
          <PriceChartSection boxStats={boxStats} />
        </Grid>
      </Grid>
    </Grid>
  );
};
