import React, { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { provincePolicyGetWageFractions } from "../../services/province-policy-get-wage-fractions";
import { Grid } from "../../../../components/grid/Grid";
import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Button,
  Checkbox,
  IconButton,
  InputAdornment,
  Tab,
  Tabs,
  TextField,
} from "@mui/material";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { ProvincePolicySubmitWage } from "../province-policy-submit-wage/ProvincePolicySubmitWage";
import { provincePolicyEditWage } from "../../services/province-policy-edit-wage";
import { AppContext } from "../../../../contexts/AppContext";
import { provincePolicyGetShareType } from "../../services/province-policy-get-wages";
import EditIcon from "@mui/icons-material/Edit";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { ProvincePolicyWagesSetupKillhouses } from "../province-policy-wage-setup-killhouses/ProvincePolicyWagesSetupKillhouses";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import SaveIcon from "@mui/icons-material/Save";

const ProvincePolicyWagesSetup = () => {
  const dispatch = useDispatch();
  const [data, setData] = useState();
  const [shareTypes, setShareTypes] = useState();
  const [dataShareTypes, setDataShareTypes] = useState();
  const [wages, setWages] = useState();
  const [openNotif] = useContext(AppContext);

  const [activeTab, setActiveTab] = useState(0);

  const handleTabChange = (event, newValue) => {
    setActiveTab(newValue);
  };

  const fetchData = () => {
    dispatch(provincePolicyGetWageFractions()).then((r) => {
      setData(r.payload.data);
    });
  };

  const fetchDataShareTypes = () => {
    dispatch(provincePolicyGetShareType()).then((r) => {
      setDataShareTypes(r.payload.data);
    });
  };

  useEffect(() => {
    if (activeTab === 0) {
      fetchData();
      fetchDataShareTypes();
    }
  }, [dispatch, activeTab]);

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        i + 1,
        item.name,
        <Checkbox
          key={i}
          checked={item.status}
          onChange={(event) => handleStatusChange(event, i, item)}
          inputProps={{ "aria-label": "controlled" }}
        />,
        <TextField
          key={i}
          style={{ width: { xs: "80px", lg: "120px" } }}
          label="مبلغ تعرفه"
          value={item.amount}
          disabled={!item.status}
          onChange={(event) => handleAmountChange(event, i)}
          size="small"
          InputProps={{
            endAdornment: <InputAdornment position="end">ریال</InputAdornment>,
          }}
        />,
        <Grid
          container
          alignItems="center"
          key={i}
          justifyContent="center"
          gap={1}
        >
          {item?.percentages?.map((percentItem, j) => (
            <TextField
              disabled={!item.status}
              style={{ width: { xs: "80px", lg: "100px" } }}
              key={j}
              label={percentItem.name}
              value={percentItem.percent}
              onChange={(event) => handlePercentageChange(event, i, j)}
              size="small"
            />
          ))}
        </Grid>,
        <IconButton
          disabled={handleValidationCheck(i) || !item.status}
          key={i}
          color="primary"
          onClick={() => handleEditClick(item)}
        >
          <SaveIcon />
        </IconButton>,
      ];
    });

    setWages(d);

    const s = dataShareTypes?.map((item, i) => {
      return [
        i + 1,
        item?.name,
        <IconButton
          key={i}
          aria-label="delete"
          color="primary"
          onClick={() => {
            dispatch(
              OPEN_MODAL({
                title: "ویرایش نقش",
                content: (
                  <ProvincePolicySubmitWage
                    itsEdit
                    fetchData={fetchData}
                    fetchDataShareTypes={fetchDataShareTypes}
                    item={item}
                  />
                ),
              })
            );
          }}
        >
          <EditIcon />
        </IconButton>,
      ];
    });

    setShareTypes(s);
  }, [data, dataShareTypes]);

  const handlePercentageChange = (event, rowIndex, percentIndex) => {
    const newData = [...data];
    newData[rowIndex].percentages[percentIndex].percent = Number(
      event.target.value
    );
    setData(newData);
  };

  const handleAmountChange = (event, rowIndex) => {
    const newData = [...data];
    newData[rowIndex].amount = Number(event.target.value);
    setData(newData);
  };
  const handleStatusChange = (event, rowIndex, item) => {
    const newData = [...data];
    newData[rowIndex].status = !newData[rowIndex].status;
    setData(newData, handleEditClick(item));
  };

  const handleValidationCheck = (index) => {
    if (data[index].percentages.length) {
      let sum = 0;
      data[index].percentages.forEach((percentItem) => {
        sum += percentItem.percent;
      });

      if (sum !== 100) {
        return true;
      } else {
        return false;
      }
    }
  };

  const handleEditClick = (item) => {
    dispatch(provincePolicyEditWage(item)).then((r) => {
      fetchData();
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  };

  return (
    <Grid container alignItems="center" justifyContent="center">
      {getRoleFromUrl() === "AdminX" && (
        <Tabs
          scrollButtons="auto"
          variant="scrollable"
          allowScrollButtonsMobile
          value={activeTab}
          onChange={handleTabChange}
        >
          <Tab label="سهامداران" />
          <Tab label="نوع تسویه" />
        </Tabs>
      )}
      {activeTab === 0 && (
        <>
          <Grid container mb={2}>
            <Button
              variant="contained"
              onClick={() => {
                dispatch(
                  OPEN_MODAL({
                    title: "افزودن نقش",
                    content: (
                      <ProvincePolicySubmitWage
                        fetchData={fetchData}
                        fetchDataShareTypes={fetchDataShareTypes}
                      />
                    ),
                  })
                );
              }}
            >
              افزودن نقش
            </Button>

            <Grid xs={12} mt={2}>
              <Accordion>
                <AccordionSummary
                  expandIcon={<ExpandMoreIcon />}
                  aria-controls="panel1-content"
                  id="panel1-header"
                >
                  سهامداران
                </AccordionSummary>
                <AccordionDetails>
                  <ResponsiveTable
                    paginated
                    columns={["ردیف", "نام", "ویرایش"]}
                    data={shareTypes}
                    title="سهامداران"
                  />
                </AccordionDetails>
              </Accordion>
            </Grid>

            <ResponsiveTable
              paginated
              title="تعرفه ها"
              columns={[
                "ردیف",
                "عنوان",
                "وضعیت",
                "مبلغ تعرفه",
                "سهم بندی",
                "ذخیره تغییرات",
              ]}
              data={wages}
            />
          </Grid>
        </>
      )}

      {activeTab === 1 && <ProvincePolicyWagesSetupKillhouses />}
    </Grid>
  );
};

export default ProvincePolicyWagesSetup;
