import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  Checkbox,
  Divider,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useDispatch } from "react-redux";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { ProvinceSendReportSendTime } from "../province-send-report-send-time/ProvinceSendReportSendTime";
import { ProvinceSendReportNewReport } from "../province-send-report-new-report/ProvinceSendReportNewReport";
import { ProvinceSendReportNewUser } from "../province-send-report-new-user/ProvinceSendReportNewUser";
import { PageTable } from "../../../../components/page-table/PageTable";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import axios from "axios";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { ProvinceSendReportOperations } from "../province-send-report-operations/ProvinceSendReportOperations";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceSendReportUpdateReportStatus } from "../../services/province-send-report-get-times";
import PublishedWithChangesIcon from "@mui/icons-material/PublishedWithChanges";
import { RiSearchLine } from "react-icons/ri";

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

  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);

  const [textValue, setTextValue] = useState("");
  const [openNotif] = useContext(AppContext);
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const fetchApiData = async (page, textValue) => {
    setLoading(true);
    const response = await axios.get(
      `reports-users/?search=filter&value=${textValue}&page=${page}&role=${getRoleFromUrl()}&page_size=${perPage}`
    );
    setData(response.data.results);
    setTotalRows(response.data.count);
    setLoading(false);
  };

  const handlePageChange = (page) => {
    fetchApiData(page, textValue);
  };

  const handlePerRowsChange = async (newPerPage, page) => {
    setLoading(true);
    const response = await axios.get(
      `reports-users/?search=filter&value=${textValue}&page=${page}&role=${getRoleFromUrl()}&page_size=${newPerPage}`
    );

    setData(response.data.results);
    setTotalRows(response.data.count);
    setPerPage(newPerPage);

    setLoading(false);
  };

  useEffect(() => {
    fetchApiData(1);
  }, []);

  const handleSubmit = async (event) => {
    event.preventDefault();
    setLoading(true);

    try {
      const response = await axios.get(
        `reports-users/?search=filter&value=${textValue}&role=${getRoleFromUrl()}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  };

  let columns = [
    {
      name: "عملیات",
      selector: (item, i) => {
        return (
          <ProvinceSendReportOperations
            item={item}
            fetchApiData={fetchApiData}
          />
        );
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "ردیف",
      selector: (item, i) => {
        return i + 1;
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "وضعیت",
      selector: (item, i) => {
        return item?.active ? "فعال" : "غیر فعال";
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "نام و نام خانوادگی",
      selector: (item, i) => {
        return item?.firstname + " " + item?.lastname;
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "موبایل",
      selector: (item, i) => {
        return item?.mobile;
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "شهر",
      selector: (item, i) => {
        return item?.city;
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "سمت",
      selector: (item, i) => {
        return getFaUserRole(item?.position);
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    // {
    //   name: "سمت",
    //   selector: (item, i) => {
    //     return item?.userPosition ? item?.userPosition : "-";
    //   },
    //   sortable: false,
    //   wrap: true,
    //   allowOverflow: true,
    //   center: true,
    // },
  ];

  const [forAll, setForAll] = useState(false);

  const setForAllFunction = (option) => {
    dispatch(
      provinceSendReportUpdateReportStatus({
        report_key: option?.report?.key,
        active: forAll,
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
        fetchApiData(1);
      }
    });
  };

  const [secondaryColumns, setSecondaryColumns] = useState([]);

  useEffect(() => {
    if (data?.length) {
      const d = data[0]?.userReports?.map((option, index) => {
        return {
          name: (
            <Grid container direction="column" alignItems="center">
              <Tooltip placement="top" title={option?.report?.description}>
                <Typography variant="body2">{option?.report?.title}</Typography>
              </Tooltip>
              <Tooltip placement="right" title={"فعال / غیر فعال برای همه"}>
                <IconButton
                  color="primary"
                  onClick={() => {
                    setForAll(!forAll, setForAllFunction(option));
                  }}
                >
                  <PublishedWithChangesIcon />
                </IconButton>
              </Tooltip>
            </Grid>
          ),
          selector: (item, i) => {
            return (
              <Checkbox
                checked={item?.userReports[index]?.active}
                name="item1"
                onClick={() => {
                  dispatch(
                    provinceSendReportUpdateReportStatus({
                      user_report_key: item?.userReports[index]?.key,
                      active: !item?.userReports[index]?.active,
                    })
                  ).then((r) => {
                    if (r.payload.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: r.payload.error,
                        severity: "error",
                      });
                    } else {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success",
                      });
                      fetchApiData(1);
                    }
                  });
                }}
              />
            );
          },
          sortable: false,
          wrap: true,
          allowOverflow: true,
          center: true,
        };
      });
      setSecondaryColumns(d);
    }
  }, [data]);

  return (
    <Grid
      container
      xs={12}
      justifyContent="center"
      alignItems="center"
      mt={2}
      mb={2}
    >
      {/* <SimpleTable
        name={
          <Grid
            container
            justifyContent="space-between"
            xs={12}
            alignItems="center"
          >
            <Grid container gap={2} alignItems="center">
              <Button
                variant="contained"
                onClick={() =>
                  dispatch(
                    OPEN_MODAL({
                      title: "گزارش جدید",
                      content: <ProvinceSendReportNewReport />,
                    })
                  )
                }
              >
                گزارش جدید
              </Button>
              <Button
                variant="contained"
                onClick={() =>
                  dispatch(
                    OPEN_MODAL({
                      title: "ثبت عضو جدید",
                      content: <ProvinceSendReportNewUser />,
                    })
                  )
                }
              >
                ثبت عضو
              </Button>
            </Grid>
            <Button
              variant="contained"
              onClick={() =>
                dispatch(
                  OPEN_MODAL({
                    title: "زمان ارسال",
                    content: <ProvinceSendReportSendTime />,
                  })
                )
              }
            >
              زمان ارسال
            </Button>
          </Grid>
        }
        data={[["1"]]}
        columns={[
          "ردیف",
          "وضعیت",
          "نام و نام خانوادگی",
          "موبایل",
          "شهر",
          "سمت",
          "گزارش مغایرت",
          "گزارش  کشتار و پخش",
          "گزارش تخصیص روزانه",
          "گزارش پایش کشتارگاه",
          "گزارش پایش کشتار",
          "گزارش توزیع مباشرین و صنف",
          "عملیات",
        ]}
      /> */}
      <Grid
        container
        justifyContent="space-between"
        xs={12}
        alignItems="center"
        style={{ width: "100%" }}
      >
        <Grid container gap={2} alignItems="center">
          <Button
            variant="contained"
            onClick={() =>
              dispatch(
                OPEN_MODAL({
                  title: "گزارش جدید",
                  content: (
                    <ProvinceSendReportNewReport fetchApiData={fetchApiData} />
                  ),
                })
              )
            }
          >
            گزارش جدید
          </Button>
          <Button
            variant="contained"
            onClick={() =>
              dispatch(
                OPEN_MODAL({
                  title: "ثبت عضو جدید",
                  content: (
                    <ProvinceSendReportNewUser fetchApiData={fetchApiData} />
                  ),
                })
              )
            }
          >
            ثبت عضو
          </Button>
        </Grid>

        <Button
          variant="contained"
          onClick={() =>
            dispatch(
              OPEN_MODAL({
                title: "زمان ارسال",
                content: (
                  <ProvinceSendReportSendTime fetchApiData={fetchApiData} />
                ),
              })
            )
          }
        >
          زمان ارسال
        </Button>
      </Grid>

      <Divider style={{ width: "100%", margin: "30px" }} />

      <Grid xs={12}>
        <PageTable
          title={
            <Grid container gap={2} alignItems="center" mb={2}>
              <Typography variant="body1">لیست گزارشات</Typography>
              <form onSubmit={handleSubmit}>
                <TextField
                  id="outlined-basic"
                  size="small"
                  autoComplete="off"
                  label="جستجو"
                  variant="outlined"
                  style={{ width: 250 }}
                  onChange={handleTextChange}
                />
                <Button
                  // disabled={!textValue}
                  type="submit"
                  onClick={handleSubmit}
                  endIcon={<RiSearchLine />}
                >
                  جستجو
                </Button>
              </form>
            </Grid>
          }
          columns={[...columns, ...secondaryColumns]}
          data={data}
          progressPending={loading}
          pagination
          paginationServer
          paginationTotalRows={totalRows}
          onChangeRowsPerPage={handlePerRowsChange}
          onChangePage={handlePageChange}
        />
      </Grid>
    </Grid>
  );
};
