import {
  Button,
  Checkbox,
  FormControlLabel,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import axios from "axios";
import { useContext, useEffect, useState } from "react";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { Grid } from "../../../../components/grid/Grid";
import { PageTable } from "../../../../components/page-table/PageTable";
import { SPACING } from "../../../../data/spacing";
import {
  ROUTE_ADMINX_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";

export const ProvincePaymentChcikenAlive = ({ type }) => {
  const authToken = useSelector((state) => state.userSlice.authToken);
  const navigate = useNavigate();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [withDate, setWithDate] = useState(false);
  const [textValue, setTextValue] = useState("");

  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, textValue) => {
    setLoading(true);
    const response = await axios.get(
      `kill_house_free_bar_total_wage/?search=filter&value=${textValue}&type=${
        type === "live_chicken" ? "live" : "carcass"
      }&page=${page}&role=${getRoleFromUrl()}&page_size=${perPage}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }`
    );
    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(
      `kill_house_free_bar_total_wage/?search=filter&value=${textValue}&type=${
        type === "live_chicken" ? "live" : "carcass"
      }&page=${page}&role=${getRoleFromUrl()}&page_size=${newPerPage}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }`
    );

    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(
        `kill_house_free_bar_total_wage/?search=filter&value=${textValue}&type=${
          type === "live_chicken" ? "live" : "carcass"
        }${withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  };

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

  const columns = [
    {
      name: "خریدار",
      selector: (item) => {
        const type = item?.info?.killer ? "کشتارکن" : "کشتارگاه";
        return `${type} ${item?.info?.killHouseName} - ${item?.info?.killHouseFullname} (${item?.info?.killHouseMobile})`;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "شهر",
      selector: (item) => `${item?.info?.killHouseCity}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "تعداد پرونده",
      selector: (item) => item?.info?.totalCount?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "حجم",
      selector: (item) => item.info?.totalQuantity?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "وزن سفارشات (کیلوگرم)",
      selector: (item) => item.info?.totalWeight?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "مبلغ کل",
      selector: (item) => `${item.info?.totalWage?.toLocaleString()} ریال`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "جزییات سفارش",
      selector: (item) => {
        return (
          <Button
            onClick={() => {
              navigate(
                `${
                  getRoleFromUrl() === "SuperAdmin"
                    ? ROUTE_SUPER_ADMIN_PAYING_FEES_REQUESTS
                    : getRoleFromUrl() === "AdminX"
                    ? ROUTE_ADMINX_PAYING_FEES_REQUESTS
                    : ROUTE_PROVINCE_PAYING_FEES_REQUESTS
                }/${type}/${item.key}`
              );
            }}
          >
            مشاهده
          </Button>
        );
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
  ];

  return (
    <Grid container justifyContent="end">
      <PageTable
        title={
          <Grid
            container
            alignItems="center"
            justifyContent="space-between"
            gap={2}
            paddingTop={2}
            mb={1}
            width="100%"
          >
            <Grid container alignItems="center" gap={SPACING.SMALL}>
              <Typography>
                خرید {type === "live_chicken" ? "مرغ زنده" : "لاشه"} آزاد
              </Typography>
              <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_wage_excel/?token=${authToken}${textValue}${
                    withDate
                      ? `&date1=${selectedDate1}&date2=${selectedDate2}`
                      : ``
                  }`}
                  rel="noreferrer"
                >
                  <Button color="success">
                    <RiFileExcel2Fill size={32} />
                  </Button>
                </a>
              </Tooltip>
            </Grid>
          </Grid>
        }
        columns={columns}
        data={data}
        progressPending={loading}
        pagination
        paginationServer
        paginationTotalRows={totalRows}
        onChangeRowsPerPage={handlePerRowsChange}
        onChangePage={handlePageChange}
      />
    </Grid>
  );
};
