import React, { useContext, useState } from "react";
import {
  Switch,
  Tooltip,
  Typography,
  Box,
  Button,
  Paper,
  useTheme,
  IconButton,
} from "@mui/material";
import { useDispatch } from "react-redux";
import { pspChangePosActiveState } from "../../services/psp-change-pos-active-state";
import { AppContext } from "../../../../contexts/AppContext";
import {
  CLOSE_MODAL,
  DRAWER,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import { motion, AnimatePresence } from "framer-motion";
import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";
import { formatJustDate } from "../../../../utils/formatTime";
import { Grid } from "../../../../components/grid/Grid";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import InfoIcon from "@mui/icons-material/Info";
import CardMembershipIcon from "@mui/icons-material/CardMembership";
import DeleteIcon from "@mui/icons-material/Delete";
import { pspRemoveSession } from "../../services/psp-remove-session";

export const PspPosList = ({ item, updateTable }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [showDetail, setShowDetail] = useState(false);
  const [posInfo, setPosInfo] = useState(null);

  const handleDeleteSession = (sessionKey) => {
    dispatch(
      OPEN_MODAL({
        title: "آیا مطمئن هستید؟",
        content: (
          <Grid container spacing={2} justifyContent="center">
            <Grid item>
              <Button
                variant="contained"
                color="error"
                onClick={() => {
                  dispatch(pspRemoveSession(sessionKey)).then((r) => {
                    if (r.payload?.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: r.payload.error,
                        severity: "error",
                      });
                    } else {
                      updateTable();
                      dispatch(CLOSE_MODAL());
                      let removedItem = posInfo?.posSessions?.findIndex(
                        (session) => session.key === sessionKey
                      );

                      posInfo?.posSessions.splice(removedItem, 1);
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "نشست با موفقیت حذف شد",
                        severity: "success",
                      });
                    }
                  });
                }}
                sx={{ mx: 1 }}
              >
                تایید حذف
              </Button>
            </Grid>
            <Grid item>
              <Button
                variant="outlined"
                onClick={() => dispatch(CLOSE_MODAL())}
                sx={{ mx: 1 }}
              >
                انصراف
              </Button>
            </Grid>
          </Grid>
        ),
      })
    );
  };
  const theme = useTheme();

  const tableData = item?.guildPos.map((pos, index) => [
    index + 1,
    pos.receiverNumber || "-",
    pos.terminalNumber || "-",
    pos.serial || "-",
    pos.posId || "-",
    pos.password || "-",
    pos.posCompany || "-",
    pos?.posSessions?.length > 0
      ? formatJustDate(pos.posSessions[0]?.sessionCreateDate)
      : "-",
    pos?.posSessions?.length > 0
      ? formatJustDate(pos.posSessions[0]?.sessionLastSeenDate)
      : "-",
    <Typography
      justifyContent="center"
      key={index}
      variant="body2"
      color={pos.posStatus ? "success.main" : "error.main"}
      sx={{
        display: "flex",
        alignItems: "center",
        gap: 0.5,
      }}
    >
      {pos?.posStatus ? "در حال استفاده" : "خاموش"}
      <InfoIcon fontSize="small" />
    </Typography>,
    <Button
      key={index}
      disabled={!pos?.posSessions.length}
      size="small"
      variant="outlined"
      color="info"
      startIcon={<CardMembershipIcon />}
      onClick={() => {
        setPosInfo(pos);
        setShowDetail(true);
      }}
      sx={{
        borderRadius: 2,
        px: 2,
        py: 0.5,
        textTransform: "none",
      }}
    >
      نمایش نشست‌ها
    </Button>,
    <Tooltip
      key={index}
      title={pos?.active ? "غیرفعال کردن" : "فعال کردن"}
      placement="bottom-start"
    >
      <Switch
        size="small"
        checked={pos.active}
        color={pos.active ? "success" : "default"}
        onChange={() => {
          dispatch(
            pspChangePosActiveState({
              pos_key: pos.key,
              active: !pos.active,
            })
          ).then((r) => {
            updateTable();
            dispatch(DRAWER({ top: false, bottom: false, content: null }));
            if (r.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "مشکلی پیش آمده است!",
                severity: "error",
              });
            } else {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
            }
          });
        }}
      />
    </Tooltip>,
  ]);

  // neshast
  const sessionsData = posInfo?.posSessions
    ?.sort((a, b) => {
      const dateA = new Date(
        a.sessionLastSeenDate || a.sessionCreateDate
      ).getTime();
      const dateB = new Date(
        b.sessionLastSeenDate || b.sessionCreateDate
      ).getTime();
      return dateB - dateA;
    })
    ?.map((session, i) => {
      const oneWeekAgo = new Date();
      oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);

      const sessionDate = new Date(
        session.sessionLastSeenDate || session.sessionCreateDate
      );

      const isLessThanOneWeek = sessionDate > oneWeekAgo;

      return [
        i + 1,
        session.name || "-",
        session.serial || "-",
        <Typography
          key={`create-${i}`}
          color={isLessThanOneWeek ? "success.main" : "text.primary"}
        >
          {formatJustDate(session.sessionCreateDate || "-")}
        </Typography>,
        <Typography
          key={`lastseen-${i}`}
          color={isLessThanOneWeek ? "success.main" : "text.primary"}
        >
          {formatJustDate(session.sessionLastSeenDate || "-")}
        </Typography>,
        <Grid container justifyContent="center" key={i}>
          <Tooltip title="حذف نشست">
            <IconButton
              color="error"
              onClick={() => {
                handleDeleteSession(session.key);
              }}
            >
              <DeleteIcon />
            </IconButton>
          </Tooltip>
        </Grid>,
      ];
    });

  return (
    <Box>
      <AnimatePresence mode="wait">
        {!showDetail ? (
          <motion.div
            key="table"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            transition={{ duration: 0.3 }}
          >
            <Paper>
              <AdvancedTable
                name={
                  <Grid container alignItems="center" gap={2} sx={{ mb: 3 }}>
                    <Grid container gap={1} alignItems="center">
                      <Typography
                        variant="body1"
                        fontWeight="bold"
                        color="primary"
                      >
                        اطلاعات دستگاه‌های POS
                      </Typography>
                      <Typography variant="caption" color="text.secondary">
                        ({item?.guildPos?.length || 0} دستگاه ثبت شده)
                      </Typography>
                    </Grid>
                  </Grid>
                }
                columns={[
                  "ردیف",
                  "شماره پذیرنده",
                  "شماره ترمینال",
                  "سریال دستگاه",
                  "کلید اتصال",
                  "کلمه عبور امنیتی",
                  "نام دستگاه",
                  "اولین ورود",
                  "آخرین بازدید",
                  "وضعیت",
                  "نشست‌ها",
                  "فعال/غیرفعال",
                ]}
                data={tableData || []}
                sx={{
                  "& .MuiTableCell-root": {
                    py: 1.5,
                  },
                  "& .MuiTableHead-root": {
                    backgroundColor: theme.palette.grey[100],
                  },
                }}
              />
            </Paper>
          </motion.div>
        ) : (
          <motion.div
            key="detail"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            transition={{ duration: 0.3 }}
          >
            <Paper elevation={0} sx={{ p: 3, borderRadius: 4 }}>
              <Grid xs={12} container justifyContent="center">
                <Grid
                  xs={12}
                  container
                  alignItems="center"
                  justifyContent="space-between"
                  sx={{ mb: 3 }}
                >
                  <Button
                    variant="outlined"
                    color="primary"
                    onClick={() => {
                      setShowDetail(false);
                    }}
                    startIcon={<ArrowBackIcon />}
                    sx={{
                      borderRadius: 2,
                      px: 3,
                      textTransform: "none",
                    }}
                  >
                    بازگشت به لیست
                  </Button>
                  <Typography variant="body1" sx={{ color: "text.primary" }}>
                    <Box component="span" color="primary.main">
                      نشست‌های فعال دستگاه
                    </Box>{" "}
                    {posInfo?.receiverNumber}
                  </Typography>
                </Grid>

                <Grid xs={12} container justifyContent="center">
                  <Paper
                    elevation={0}
                    sx={{
                      width: "100%",
                      p: 2,
                      borderRadius: 4,
                      backgroundColor: theme.palette.grey[50],
                    }}
                  >
                    <SimpleTable
                      name="نشست های فعال"
                      columns={[
                        "ردیف",
                        "نشست های فعال ",
                        "سریال",
                        "تاریخ ایجاد",
                        "آخرین بازدید",
                        "عملیات",
                      ]}
                      data={sessionsData}
                    />
                  </Paper>
                </Grid>
              </Grid>
            </Paper>
          </motion.div>
        )}
      </AnimatePresence>
    </Box>
  );
};
