import React, { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { motion } from "framer-motion";
import {
  Typography,
  Box,
  Card,
  CardContent,
  Grid,
  Divider,
  Pagination,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
} from "@mui/material";
import PersonIcon from "@mui/icons-material/Person";
import PhoneIcon from "@mui/icons-material/Phone";
import InventoryIcon from "@mui/icons-material/Inventory";
import { DatePicker } from "@mui/x-date-pickers";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import ErrorIcon from "@mui/icons-material/Error";
import Chip from "@mui/material/Chip";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getStewardTransactions } from "../../services/getStewardTransactions";
import { convertToIranianTime } from "../../../../utils/formatTime";
import { getPosProviderName } from "../../../../utils/getPosProviderName";
import { AppContext } from "../../../../contexts/AppContext";
import moment from "moment";

const MainPlaceFullInfo = ({ item }) => {
  const dispatch = useDispatch();
  const [transactionData, setTransactionData] = useState();
  const [page, setPage] = useState(1);
  const [transactionMode, setTransactionMode] = useState("0");

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [renderFinished, setRenderFinished] = useState(false);

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
    setRenderFinished(true);
  }, []);

  const fetchTransactions = (pageIndex) => {
    dispatch(LOADING_START());
    dispatch(
      getStewardTransactions({
        key: item.shop,
        datefrom: convertToIranianTime(selectedDate1),
        dateto: convertToIranianTime(selectedDate2),
        page: pageIndex,
        mode: transactionMode,
      })
    ).then((r) => {
      dispatch(LOADING_END());
      setTransactionData(r.payload.data);
    });
  };

  useEffect(() => {
    if (renderFinished) {
      fetchTransactions(1);
    }
  }, [selectedDate1, selectedDate2, renderFinished, transactionMode]);

  const handleChangePage = (newPage) => {
    setPage(newPage);
    fetchTransactions(newPage);
  };

  const handleChangeTransactionMode = (event) => {
    setTransactionMode(event.target.value);
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: -50 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -50 }}
      transition={{ duration: 0.5 }}
    >
      <Grid container justifyContent="center" style={{ overflowX: "hidden" }}>
        <Grid container justifyContent="center" spacing={2} xs={12}>
          <Grid item xs={12} sm={4} md={4}>
            <motion.div
              initial={{ opacity: 0, x: -50 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.2 }}
            >
              <Box
                display="flex"
                alignItems="center"
                justifyContent={{ xs: "flex-start", sm: "center" }}
              >
                <PersonIcon />
                <Typography variant="body2" color="textSecondary">
                  نام مالک: {item.guild_info.fullname}
                </Typography>
              </Box>
            </motion.div>
          </Grid>
          <Grid item xs={12} sm={4} md={4}>
            <motion.div
              initial={{ opacity: 0, x: -50 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.4 }}
            >
              <Box
                display="flex"
                alignItems="center"
                justifyContent={{ xs: "flex-start", sm: "center" }}
              >
                {" "}
                <PhoneIcon sx={{ mr: 1 }} />
                <Typography variant="body2" color="textSecondary">
                  شماره همراه: {item.guild_info.mobile}
                </Typography>
              </Box>
            </motion.div>
          </Grid>
          <Grid item xs={12} sm={4} md={4}>
            <motion.div
              initial={{ opacity: 0, x: -50 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.6 }}
            >
              <Box
                display="flex"
                alignItems="center"
                justifyContent={{ xs: "flex-start", sm: "center" }}
              >
                {" "}
                <InventoryIcon sx={{ mr: 1 }} />
                <Typography variant="body2" color="textSecondary">
                  موجودی: {item?.ware_house_info.quantity.toLocaleString()}
                </Typography>
              </Box>
            </motion.div>
          </Grid>
        </Grid>

        <Grid
          container
          justifyContent="center"
          spacing={2}
          sx={{ my: 2 }}
          alignItems="center"
        >
          <Grid item xs={12} sm={6} md={3}>
            <motion.div
              initial={{ opacity: 0, y: -50 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.8 }}
            >
              <DatePicker
                label="از تاریخ"
                id="date"
                renderInput={(params) => <TextField {...params} />}
                value={selectedDate1}
                onChange={(e) => {
                  setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </motion.div>
          </Grid>
          <Grid item xs={12} sm={6} md={3}>
            <motion.div
              initial={{ opacity: 0, y: -50 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 1.0 }}
            >
              <DatePicker
                label="تا تاریخ"
                id="date"
                renderInput={(params) => <TextField {...params} />}
                value={selectedDate2}
                onChange={(e) => {
                  setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </motion.div>
          </Grid>

          <Grid item xs={12} sm={6} md={3}>
            <motion.div
              initial={{ opacity: 0, y: -50 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 1.0 }}
            >
              <FormControl fullWidth>
                <InputLabel id="demo-simple-select-label">
                  فیلتر تراکنش ها
                </InputLabel>
                <Select
                  labelId="demo-simple-select-label"
                  id="demo-simple-select"
                  value={transactionMode}
                  label="Age"
                  onChange={handleChangeTransactionMode}
                >
                  <MenuItem value={"0"}>همه</MenuItem>
                  <MenuItem value={"1"}>موفق</MenuItem>
                  <MenuItem value={"3"}>ناموفق</MenuItem>
                  <MenuItem value={"2"}>نسیه</MenuItem>
                </Select>
              </FormControl>
            </motion.div>
          </Grid>
        </Grid>
        <Divider style={{ width: "100%" }}>
          <Chip
            label={`تعداد کل تراکنش ها: ${
              transactionData?.totalItems ? transactionData?.totalItems : 0
            } ، جمع کل: ${transactionData?.sum.toLocaleString()} ریال`}
          />
        </Divider>
        <Grid container justifyContent="center" spacing={2} mt={2} p={2}>
          {transactionData?.items?.map((item, index) => (
            <Grid item xs={12} sm={6} md={3} key={index} className="bluehover">
              <motion.div
                initial={{ opacity: 0, scale: 0.5 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ delay: index * 0.1 + 1.2 }}
              >
                <Card
                  style={{
                    width: "100%",
                    height: "100%",
                    backgroundColor: !item?.name.includes("موفق")
                      ? "rgb(255 229 229)"
                      : "white",
                  }}
                >
                  <CardContent>
                    <Box display="flex" alignItems="center">
                      <Typography
                        variant="h6"
                        component="h2"
                        style={{ marginRight: "8px" }}
                      >
                        {page > 1 ? page * 20 - 20 + index + 1 : index + 1} -
                      </Typography>
                      <Typography
                        variant={item?.name.length < 17 ? "h6" : "body1"}
                        component="h2"
                        style={{ marginRight: "8px" }}
                      >
                        {item?.name}
                      </Typography>
                      {!item?.name.includes("موفق") ? (
                        <ErrorIcon
                          style={{ color: "red", marginRight: "4px" }}
                        />
                      ) : (
                        <CheckCircleIcon
                          style={{ color: "green", marginRight: "4px" }}
                        />
                      )}
                    </Box>
                    <Divider />
                    <Grid display="grid" gap={2} mt={2}>
                      <Typography variant="body2">
                        <strong>تاریخ:</strong>{" "}
                        {convertToIranianTime(item?.date)}
                      </Typography>
                      {item?.product.length === 1 && (
                        <Typography variant="body2">
                          <strong>محصول:</strong> {item?.product[0]?.name}
                        </Typography>
                      )}
                      {item?.product.length > 1 && (
                        <Typography variant="body2">
                          <strong>محصولات:</strong>{" "}
                          {item?.product?.map((productItem, index) => (
                            <span key={index}>{productItem.name} / </span>
                          ))}
                        </Typography>
                      )}
                      <Typography variant="body2">
                        <strong>مبلغ:</strong> {item?.price.toLocaleString()}{" "}
                        ریال
                      </Typography>
                      <Typography variant="body2">
                        <strong>از سرویس:</strong>{" "}
                        {getPosProviderName(item?.posProvider)}
                      </Typography>
                    </Grid>
                  </CardContent>
                </Card>
              </motion.div>
            </Grid>
          ))}
        </Grid>
        <Grid mt={2}>
          <motion.div
            initial={{ opacity: 0, y: 50 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: transactionData?.items?.length * 0.1 + 1.5 }}
          >
            <Pagination
              count={Math.ceil(transactionData?.totalItems / 20)}
              page={page}
              variant="outlined"
              onChange={(event, newPage) => {
                handleChangePage(newPage);
              }}
            />
          </motion.div>
        </Grid>
      </Grid>
    </motion.div>
  );
};

export default MainPlaceFullInfo;
