import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  Checkbox,
  FormControlLabel,
  IconButton,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useDispatch } from "react-redux";
import {
  getDocumentStates,
  submitDocumentStates,
} from "../../services/getDocumentStates";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import {
  provincePolicyDeleteDocumentState,
  provincePolicyEditDocumentState,
  provincePolicySubmitDocumentState,
} from "../../services/province-policy-submit-document-state";
import { AppContext } from "../../../../contexts/AppContext";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import TuneIcon from "@mui/icons-material/Tune";

// import { AppContext } from "../../../../contexts/AppContext";

export const ProvincePolicyDocumentStates = () => {
  const dispatch = useDispatch();
  const [tableData, setTableData] = useState([]);
  const [editPriorityMode, setEditPriorityMode] = useState(false);
  const [priorities, setPriorities] = useState([]);
  const [data, setData] = useState([]);

  const handleTextChange = (event, i) => {
    const newlist = [...priorities];
    newlist[i] = { ...newlist[i], value: parseInt(event.target.value) };
    setPriorities(newlist);
  };

  const [openNotif] = useContext(AppContext);

  const fetchData = () => {
    dispatch(getDocumentStates()).then((r) => {
      setData(r.payload.data);
      const fields = r.payload.data?.map((item) => {
        return { key: item?.key, value: item?.priorityId };
      });
      setPriorities(fields);
    });
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        editPriorityMode ? (
          <TextField
            key={i}
            id="outlined-basic"
            size="small"
            label="جستجو"
            variant="outlined"
            style={{ width: 100 }}
            value={priorities[i]?.value || item?.priorityId}
            onChange={(e) => handleTextChange(e, i)}
          />
        ) : (
          item?.priorityId
        ),
        item?.title,
        item?.sms ? "دارد" : "ندارد",
        item?.isError ? (
          <Typography key={i} color="error" variant="body2">
            ندارد
          </Typography>
        ) : (
          <Typography key={i} color="primary" variant="body2">
            دارد
          </Typography>
        ),
        <Grid container key={i} justifyContent="center">
          <DocumentStateActions
            onEdit={() => {
              dispatch(
                OPEN_MODAL({
                  title: "ویرایش وضعیت",
                  content: (
                    <ProvincePolicyDocumentStatesModal
                      fetchData={fetchData}
                      isEdit
                      item={item}
                    />
                  ),
                })
              );
            }}
            onDelete={() => {
              dispatch(provincePolicyDeleteDocumentState(item?.id)).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",
                    });
                  }
                }
              );
            }}
          />
        </Grid>,
      ];
    });
    setTableData(d);
  }, [data, priorities, editPriorityMode]);

  useEffect(() => {
    fetchData();
  }, []);

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

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

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

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

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

    return (
      <Grid>
        <Tooltip title="تنظیمات">
          <IconButton color="primary" 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>
    );
  };

  return (
    <Grid container xs={12} alignItems="center" justifyContent="space-between">
      <Grid
        container
        style={{ width: "100%" }}
        mt={2}
        alignItems="center"
        gap={2}
      >
        <Typography variant="body1">وضعیت اسناد</Typography>
        <Grid container alignItems="center" gap={1}>
          <Button
            variant="contained"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "ایجاد وضعیت جدید",
                  content: (
                    <ProvincePolicyDocumentStatesModal fetchData={fetchData} />
                  ),
                })
              );
            }}
          >
            ساخت وضعیت جدید
          </Button>
          {editPriorityMode ? (
            <Grid container alignItems="center" gap={1}>
              <Button
                variant="contained"
                onClick={() => {
                  dispatch(
                    submitDocumentStates({ priority_list: priorities })
                  ).then((r) => {
                    if (r.payload.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: r.payload.error,
                        severity: "error",
                      });
                    } else {
                      fetchData();
                      editPriorityMode(false);
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success",
                      });
                    }
                  });
                }}
              >
                ذخیره تغییرات
              </Button>
              <Button
                variant="contained"
                onClick={() => {
                  setEditPriorityMode(false);
                }}
                color="error"
              >
                لغو
              </Button>
            </Grid>
          ) : (
            <Button
              variant="contained"
              onClick={() => {
                setEditPriorityMode(true);
              }}
            >
              ویرایش اولویت ها
            </Button>
          )}
        </Grid>
        <SimpleTable
          style={{ width: "100%" }}
          columns={[
            "اولویت",
            "عنوان",
            "ارسال پیامک",
            "مجوز ویرایش سند",
            "عملیات",
          ]}
          data={tableData}
        />
      </Grid>
    </Grid>
  );
};

const ProvincePolicyDocumentStatesModal = ({ fetchData, isEdit, item }) => {
  const [sms, setSms] = useState(item?.sms ? true : false);
  const [isError, setIsError] = useState(item?.isError ? true : false);
  const dispatch = useDispatch();
  const handleChangeSms = (event) => {
    setSms(event.target.checked);
  };

  const handleChangeIsError = (event) => {
    setIsError(event.target.checked);
  };

  const formik = useFormik({
    initialValues: {
      stateTitle: item?.title ? item?.title : "",
      priority: item?.priorityId ? item?.priorityId : 1,
    },
    validationSchema: Yup.object({
      stateTitle: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عنوان وضعیت را وارد کنید!"),
      priority: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عنوان وضعیت را وارد کنید!")
        .min(1, "عدد مثبت وارد کنید!"),
    }),
  });

  useEffect(() => {
    formik.validateForm();
  }, []);

  const [openNotif] = useContext(AppContext);

  return (
    <Grid container xs={12} alignItems="center" justifyContent="center" gap={1}>
      <TextField
        fullWidth
        id="stateTitle"
        label="عنوان وضعیت"
        value={formik.values.stateTitle}
        error={
          formik.touched.stateTitle ? Boolean(formik.errors.stateTitle) : null
        }
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.stateTitle && Boolean(formik.errors.stateTitle)
            ? formik.errors.stateTitle
            : null
        }
        autoComplete="current-password"
        variant="outlined"
      />
      {isEdit && (
        <TextField
          fullWidth
          id="priority"
          label="اولویت"
          value={formik.values.priority}
          error={
            formik.touched.priority ? Boolean(formik.errors.priority) : null
          }
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.priority && Boolean(formik.errors.priority)
              ? formik.errors.priority
              : null
          }
          autoComplete="current-password"
          variant="outlined"
        />
      )}

      <Grid container>
        <FormControlLabel
          control={
            <Checkbox
              checked={sms}
              onChange={handleChangeSms}
              inputProps={{ "aria-label": "controlled" }}
            />
          }
          label="ارسال پیامک"
        />

        <FormControlLabel
          control={
            <Checkbox
              checked={isError}
              onChange={handleChangeIsError}
              inputProps={{ "aria-label": "controlled" }}
            />
          }
          label="محدود کننده"
        />
      </Grid>

      <Button
        disabled={!formik.isValid}
        variant="contained"
        fullWidth
        onClick={() => {
          if (isEdit) {
            dispatch(
              provincePolicyEditDocumentState({
                title: formik.values.stateTitle,
                sms: sms,
                is_error: isError,
                bar_documents_status_key: item?.key,
                priority_id: formik.values.priority,
              })
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                fetchData();
                dispatch(CLOSE_MODAL());
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          } else {
            dispatch(
              provincePolicySubmitDocumentState({
                title: formik.values.stateTitle,
                sms: sms,
                is_error: isError,
              })
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                fetchData();
                dispatch(CLOSE_MODAL());
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
