import {
  Button,
  Checkbox,
  FormControlLabel,
  IconButton,
  TextField,
  Tooltip,
} from "@mui/material";
import axios from "axios";
import { useContext, useEffect, useState } from "react";
import { RiFileExcel2Fill } from "react-icons/ri";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import {
  ROUTE_ADMINX_PAYING_FEES_REQUESTS,
  ROUTE_COMMERCE_PAYING_FEES_REQUESTS,
  ROUTE_PROVINCE_PAYING_FEES_REQUESTS,
  ROUTE_SUPER_ADMIN_PAYING_FEES_REQUESTS,
} from "../../../../routes/routes";
import moment from "moment";
import { DatePicker } from "@mui/x-date-pickers";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { RiSearchLine } from "react-icons/ri";
import VisibilityIcon from "@mui/icons-material/Visibility";

export const ProvincePaidFees = () => {
  const navigate = useNavigate();
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [withDate, setWithDate] = useState(false);
  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  const [textValue, setTextValue] = useState("");
  const [tableData, setTableData] = useState([]);
  const [page, setPage] = useState(1);
  const dispatch = useDispatch();

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `kill_house_total_transactions_wage/?search=filter&value=${textValue}&type=paid&page=${page}&role=${getRoleFromUrl()}&page_size=${perPage}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }`
    );
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };
  useEffect(() => {
    fetchApiData(1);
  }, []);

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `kill_house_total_transactions_wage/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&type=paid${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

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

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        `${item?.info?.killer ? "کشتارکن" : "کشتارگاه"} ${
          item?.info?.killHouseName
        } - ${item?.info?.killHouseFullname} (${item?.info?.killHouseMobile})`,
        `${item?.info?.killHouseCity}`,
        item?.info?.totalPaidCount,
        item?.info?.totalPaidWage?.toLocaleString(),
        <IconButton
          key={i}
          size="small"
          color="success"
          onClick={() => {
            navigate(
              getRoleFromUrl() === "ProvinceOperator"
                ? `${ROUTE_PROVINCE_PAYING_FEES_REQUESTS}/kill_house_key/${item.key}`
                : getRoleFromUrl() === "SuperAdmin"
                ? `${ROUTE_SUPER_ADMIN_PAYING_FEES_REQUESTS}/kill_house_key/${item.key}`
                : getRoleFromUrl() === "AdminX"
                ? `${ROUTE_ADMINX_PAYING_FEES_REQUESTS}/kill_house_key/${item.key}`
                : getRoleFromUrl() === "Commerce"
                ? `${ROUTE_COMMERCE_PAYING_FEES_REQUESTS}/kill_house_key/${item.key}`
                : "-"
            );
          }}
        >
          <VisibilityIcon fontSize="small" />
        </IconButton>,
      ];
    });

    setTableData(d);
  }, [data]);

  return (
    <Grid container justifyContent="end">
      <Grid
        container
        alignItems="center"
        justifyContent="space-between"
        gap={2}
        paddingTop={2}
        mb={1}
        width="100%"
      >
        <Grid container alignItems="center" gap={SPACING.SMALL}>
          <Grid
            container
            style={{
              borderStyle: "solid",
              borderWidth: "1px",
              padding: "10px",
              borderRadius: "15px",
              borderColor: "gray",
              justifyContent: "left",
            }}
          >
            <Grid>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={withDate}
                    onChange={() => setWithDate(!withDate)}
                    color="primary"
                  />
                }
              />
            </Grid>
            <Grid>
              <DatePicker
                disabled={!withDate}
                label="از تاریخ"
                id="date"
                renderInput={(params) => (
                  <TextField
                    size="small"
                    style={{ width: "160px" }}
                    {...params}
                  />
                )}
                value={selectedDate1}
                onChange={(e) => {
                  setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </Grid>
            <Grid>
              <DatePicker
                disabled={!withDate}
                label="تا تاریخ"
                id="date"
                renderInput={(params) => (
                  <TextField
                    size="small"
                    style={{ width: "160px" }}
                    {...params}
                  />
                )}
                value={selectedDate2}
                onChange={(e) => {
                  setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </Grid>
          </Grid>
          <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>
          <Tooltip title="خروجی اکسل">
            <a
              href={`${
                axios.defaults.baseURL
              }kill_house_total_transactions_wage_payid_excel/?key=${userKey}&search=filter&value=${textValue}${
                withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
              }&role=${getRoleFromUrl()}`}
              rel="noreferrer"
            >
              <Button color="success">
                <RiFileExcel2Fill size={32} />
              </Button>
            </a>
          </Tooltip>
        </Grid>
      </Grid>
      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "خریدار",
          "شهر",
          "تعداد تراکنش",
          "مبلغ (﷼)",
          "جزییات سفارش",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="پرداختی های کشتارگاه ها"
      />
    </Grid>
  );
};
