import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { useDispatch } from "react-redux";
import {
  provincePolicyEditBeneficiaryAccountsSevice,
  provincePolicyGetAccountsSevice,
  provincePolicyGetBeneficiaryAccountsSevice,
} from "../../services/province-policy-get-accounts";
import { DRAWER, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { Button, Checkbox, IconButton, Tab, Tabs } from "@mui/material";
import EditIcon from "@mui/icons-material/Edit";
import { ProvincePolicyAccountsEditAccount } from "../province-policy-accounts-edit-account/ProvincePolicyAccountsEditAccount";
import { ProvincePolicyAccountsSubmitBeneficiary } from "../province-policy-accounts-submit-beneficiary/ProvincePolicyAccountsSubmitBeneficiary";
import { ProvincePolicyAccountsOperations } from "../province-policy-accounts-operations/ProvincePolicyAccountsOperations";
import { AppContext } from "../../../../contexts/AppContext";

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

  const [tableData, setTableData] = useState();
  const [tableBeneficiaryData, setTableBeneficiaryData] = useState();
  const [data, setData] = useState();
  const [beneficiaryData, setBeneficiaryData] = useState();

  const [value, setValue] = useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

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

  const [openNotif] = useContext(AppContext);

  const handleFinishSubmit = (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",
      });
    }
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        i + 1,
        item?.name,
        item?.account,

        <IconButton
          key={i}
          aria-label="delete"
          color="primary"
          className="avicultureActiveRequestsBtn"
          onClick={() => {
            // dispatch(inspectorUpdateUserProfile());
            dispatch(
              OPEN_MODAL({
                title: "ویرایش حساب",
                content: (
                  <ProvincePolicyAccountsEditAccount
                    item={item}
                    fetchData={fetchData}
                  />
                ),
              })
            );
          }}
        >
          <EditIcon />
        </IconButton>,
      ];
    });

    setTableData(d);

    const b = beneficiaryData?.map((option, index) => {
      return [
        index + 1,
        option?.name,
        option?.percent,
        option?.shaba,
        <Checkbox
          key={index}
          checked={option.inProvince}
          onChange={() =>
            dispatch(
              provincePolicyEditBeneficiaryAccountsSevice({
                in_province: !option?.inProvince,
                account_key: option?.key,
              })
            ).then((r) => {
              handleFinishSubmit(r);
            })
          }
        />,
        <Checkbox
          key={index}
          checked={option?.outProvince}
          onChange={() =>
            dispatch(
              provincePolicyEditBeneficiaryAccountsSevice({
                out_province: !option?.outProvince,
                account_key: option?.key,
              })
            ).then((r) => {
              handleFinishSubmit(r);
            })
          }
        />,
        <ProvincePolicyAccountsOperations
          key={index}
          item={option}
          fetchData={fetchData}
        />,
      ];
    });

    setTableBeneficiaryData(b);
  }, [data, beneficiaryData]);

  useEffect(() => {
    fetchData();
  }, [dispatch, value]);
  return (
    <Grid container xs={12} justifyContent="center" alignItems="center">
      <Tabs
        scrollButtons="auto"
        variant="scrollable"
        allowScrollButtonsMobile
        value={value}
        onChange={handleChange}
      >
        <Tab label="حساب ها" value={0} />
        <Tab label="حساب های ذینفع" value={1} />
      </Tabs>

      {value === 0 && (
        <ResponsiveTable
          noPagination
          columns={["ردیف", "نام", "شماره حساب", "ویرایش"]}
          data={tableData}
          title={"حساب ها"}
          customColors={[
            { name: "تعداد تخصیص بدون بار", color: "yellow" },
            { name: "نام", color: "cyan" },
            { name: "شماره حساب", color: "orange" },
          ]}
        />
      )}

      {value === 1 && (
        <Grid xs={12} container mt={2}>
          <Button
            variant="contained"
            onClick={() => {
              dispatch(
                DRAWER({
                  right: !(window.innerWidth <= 600),
                  bottom: window.innerWidth <= 600,
                  content: (
                    <ProvincePolicyAccountsSubmitBeneficiary
                      fetchData={fetchData}
                    />
                  ),
                  title: " افزودن حساب ذینفع",
                })
              );
            }}
          >
            افزودن حساب ذینفع
          </Button>
          <ResponsiveTable
            noPagination
            columns={[
              "ردیف",
              "نام ذینفع",
              "درصد سهم",
              "شماره شبا",
              "سهم داخل استان",
              "سهم خارج استان",
              "عملیات",
            ]}
            data={tableBeneficiaryData}
            title={"حساب های ذینفع"}
          />
        </Grid>
      )}
    </Grid>
  );
};
