import { Button, Checkbox, TextField, Typography } from "@mui/material";
import React, { useContext, useEffect, useState } from "react";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { Grid } from "../../../../components/grid/Grid";
import { PageTable } from "../../../../components/page-table/PageTable";
import axios from "axios";
import { SPACING } from "../../../../data/spacing";
import { provinceUpdateMobileMessagesActiveService } from "../../services/province-get-mobile-messages";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch } from "react-redux";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { ProvincePolicyMobileMessageSubmit } from "../province-policy-mobile-message-submit/ProvincePolicyMobileMessageSubmit";
import { ProvincePolicyMobileMessageOperations } from "../province-policy-mobile-message-operations/ProvincePolicyMobileMessageOperations";
import { RiSearchLine } from "react-icons/ri";

export const ProvincePolicyMobileMessage = () => {
  const [openNotif] = useContext(AppContext);
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const dispatch = useDispatch();
  const fetchApiData = async (page, textValue) => {
    setLoading(true);
    const response = await axios.get(
      `moving-text/?search=filter&value=${textValue}&page=${page}&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(
      `moving-text/?search=filter&value=${textValue}&page=${page}&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(
        `moving-text/?search=filter&value=${textValue}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  };

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

  const columns = [
    {
      name: "ردیف",
      selector: (item, i) => i + 1,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "60px",
    },
    {
      name: "عملیات",
      selector: (item) => (
        <ProvincePolicyMobileMessageOperations
          fetchApiData={fetchApiData}
          item={item}
        />
      ),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "وضعیت",
      selector: (item) => (item?.active ? "فعال" : "غیر فعال"),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },

    {
      name: "متن",
      selector: (item) => item?.movingText,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
  ];

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

  useEffect(() => {
    if (data?.length) {
      const d = data[0]?.roles?.map((option, index) => {
        return {
          name: (
            <Typography variant="body2">
              {getFaUserRole(option?.role)}
            </Typography>
          ),
          selector: (item) => {
            return (
              <Checkbox
                checked={item?.roles[index]?.active}
                name="item1"
                onClick={() => {
                  dispatch(
                    provinceUpdateMobileMessagesActiveService({
                      moving_text_role_key: item?.roles[index]?.key,
                      active: !item?.roles[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]);

  const tableTitle = (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={2}
      paddingTop={2}
      mb={1}
    >
      <Grid container alignItems="center" gap={SPACING.SMALL}>
        <Typography>متن متحرک </Typography>
        <form onSubmit={handleSubmit}>
          <TextField
            id="outlined-basic"
            size="small"
            label="جستجو"
            variant="outlined"
            style={{ width: 250 }}
            onChange={handleTextChange}
          />
          <Button
            // disabled={!textValue}
            type="submit"
            onClick={handleSubmit}
            endIcon={<RiSearchLine />}
          >
            جستجو
          </Button>
        </form>
      </Grid>
    </Grid>
  );

  return (
    <Grid alignItems="center" justifyContent="center" mt={4}>
      <Grid container>
        <Button
          variant="contained"
          onClick={() => {
            dispatch(
              OPEN_MODAL({
                title: "ثبت متن متحرک",
                content: (
                  <ProvincePolicyMobileMessageSubmit
                    fetchApiData={fetchApiData}
                  />
                ),
              })
            );
          }}
        >
          متن جدید
        </Button>
      </Grid>
      <PageTable
        title={tableTitle}
        columns={[...columns, ...secondaryColumns]}
        data={data}
        progressPending={loading}
        pagination
        paginationServer
        paginationTotalRows={totalRows}
        onChangeRowsPerPage={handlePerRowsChange}
        onChangePage={handlePageChange}
      />
    </Grid>
  );
};
