import React, { useContext, useEffect, useState } from "react";
import {
  TextField,
  Button,
  Grid,
  IconButton,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
  Tooltip,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import * as Yup from "yup";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { useDispatch } from "react-redux";
import {
  provinceDeleteAgeMessagesService,
  provinceGetAgeMessagesService,
  provinceSubmitAgeMessagesService,
} from "../../services/province-age-message";
import { formatJustDate } from "../../../../utils/formatTime";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import TuneIcon from "@mui/icons-material/Tune";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { ProvinceEditAgeMessage } from "../province-edit-age-message/ProvinceEditAgeMessage";
import { AppContext } from "../../../../contexts/AppContext";

export const ProvinceAgeMessage = () => {
  const [tableData, setTableData] = useState([]);
  const [openNotif] = useContext(AppContext);

  const dispatch = useDispatch();
  const validationSchema = Yup.object({
    ageRange: Yup.number()
      .required("بازه سنی ضروری است")
      .max(99, "عدد دورقمی وارد کنید!"),
    lossPercent: Yup.number()
      .required("درصد افت ضروری است")
      .max(99, "عدد دورقمی وارد کنید!"),
    message: Yup.string()
      .required("پیغام ضروری است")
      .max(500, "حداکثر 500 کاراکتر"),
  });

  const formik = useFormik({
    initialValues: {
      ageRange: "",
      message: "",
      lossPercent: "",
    },
    validationSchema,
    onSubmit: (values, { resetForm }) => {
      dispatch(
        provinceSubmitAgeMessagesService({
          message: values.message,
          poultry_age: values.ageRange,
          losses_percent: values.lossPercent,
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          fetchData();
          resetForm();
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    },
  });

  const fetchData = () => {
    dispatch(provinceGetAgeMessagesService()).then((r) => {
      const d = r.payload.data?.map((item, i) => {
        return [
          i + 1,
          formatJustDate(item?.createDate),
          item?.lossesPercent,
          item?.poultryAge,
          item?.message,
          <Grid justifyContent="center" alignItems="center" key={i}>
            <ProvinceAgeMessageActions
              item={item}
              onDelete={() => {
                dispatch(provinceDeleteAgeMessagesService(item?.key)).then(
                  (r) => {
                    if (r.payload.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: r.payload.error,
                        severity: "error",
                      });
                    } else {
                      fetchData();
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success",
                      });
                    }
                  }
                );
              }}
              onEdit={() => {
                dispatch(
                  DRAWER({
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    title: "ویرایش خریدار",
                    content: (
                      <ProvinceEditAgeMessage
                        isEdit
                        item={item}
                        fetchData={fetchData}
                      />
                    ),
                  })
                );
              }}
            />
          </Grid>,
        ];
      });
      setTableData(d);
    });
  };

  const ProvinceAgeMessageActions = ({ onDelete, onEdit }) => {
    const [anchorEl, setAnchorEl] = useState(null);
    const open = Boolean(anchorEl);

    const handleOpen = (event) => {
      setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
      setAnchorEl(null);
    };

    const handleDelete = () => {
      onDelete();
      handleClose();
    };

    const handleEdit = () => {
      onEdit();
      handleClose();
    };

    return (
      <Grid>
        <Tooltip title="تنظیمات">
          <IconButton
            color="primary"
            className="avicultureActiveRequestsBtn"
            onClick={handleOpen}
          >
            <TuneIcon />
          </IconButton>
        </Tooltip>
        <Popover
          open={open}
          anchorEl={anchorEl}
          onClose={handleClose}
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "right",
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "left",
          }}
        >
          <List sx={{ minWidth: 140, p: 1 }}>
            <ListItemButton onClick={handleEdit} sx={{ py: 1 }}>
              <ListItemIcon>
                <EditIcon color="primary" />
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography variant="body2" color="textPrimary">
                    ویرایش
                  </Typography>
                }
              />
            </ListItemButton>
            <ListItemButton onClick={handleDelete} sx={{ py: 1 }}>
              <ListItemIcon>
                <DeleteIcon color="error" />
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography variant="body2" color="textPrimary">
                    حذف
                  </Typography>
                }
              />
            </ListItemButton>
          </List>
        </Popover>
      </Grid>
    );
  };

  useEffect(() => {
    fetchData();
  }, [dispatch]);
  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container justifyContent="space-between" xs={12} spacing={2}>
        <Grid container spacing={2} xs={12} sm={6}>
          <Grid item xs={6}>
            <TextField
              fullWidth
              id="ageRange"
              name="ageRange"
              label="بازه سنی"
              variant="outlined"
              value={formik.values.ageRange}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              error={formik.touched.ageRange && Boolean(formik.errors.ageRange)}
              helperText={formik.touched.ageRange && formik.errors.ageRange}
            />
          </Grid>
          <Grid item xs={6}>
            <TextField
              fullWidth
              id="lossPercent"
              name="lossPercent"
              label="درصد افت"
              variant="outlined"
              value={formik.values.lossPercent}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              error={
                formik.touched.lossPercent && Boolean(formik.errors.lossPercent)
              }
              helperText={
                formik.touched.lossPercent && formik.errors.lossPercent
              }
            />
          </Grid>
          <Grid item xs={12}>
            <TextField
              fullWidth
              multiline
              rows={5}
              id="message"
              name="message"
              label="پیغام"
              variant="outlined"
              value={formik.values.message}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              error={formik.touched.message && Boolean(formik.errors.message)}
              helperText={formik.touched.message && formik.errors.message}
            />
          </Grid>
          <Grid item xs={12}>
            <Button type="submit" variant="contained" color="primary" fullWidth>
              ثبت
            </Button>
          </Grid>
        </Grid>
        <Grid container spacing={2} xs={12} sm={6}>
          <ResponsiveTable
            title="پیغام بازه سنی"
            paginated
            columns={[
              "ردیف",
              "تاریخ ثبت",
              "درصد افت",
              "بازه سنی",
              "متن پیام",
              "عملیات",
            ]}
            data={tableData}
          />
        </Grid>
      </Grid>
    </form>
  );
};
