import {
  Button,
  Checkbox,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import axios from "axios";
import { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { PageTable } from "../../../../components/page-table/PageTable";
import { SPACING } from "../../../../data/spacing";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { format } from "date-fns-jalali";
import { RiFileExcel2Fill } from "react-icons/ri";
import { useSelector } from "react-redux";

export const ProvinceDailyBarsDetails = ({ killhouseKey, type }) => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [openNotif] = useContext(AppContext);
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

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

  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 fetchApiData = async (page, textValue) => {
    setLoading(true);
    const response = await axios.get(
      `kill_house_request_bar_management_wage/?search=filter&value=${textValue}&page=${page}&page_size=${perPage}&type=paid&kill_house_key=${killhouseKey}&role=${getRoleFromUrl()}&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_request_bar_management_wage/?search=filter&value=${textValue}&page=${page}&page_size=${newPerPage}&type=paid&kill_house_key=${killhouseKey}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}`
    );

    setData(response.data.results);
    setTotalRows(response.data.count);
    setPerPage(newPerPage);

    setLoading(false);
  };

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

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    setLoading(true);

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

  const columns = [
    {
      name: "کد بار",
      selector: (item) => {
        return item.barCode;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "خریدار",
      selector: (item) => {
        return `${item.killhouseUser?.name} (${item.killhouseUser?.killHouseOperator?.user?.mobile})`;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "ماشین",
      selector: (item) => {
        return `${item.addCar.driver.typeCar} ${item.addCar.driver.pelak}`;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "راننده",
      selector: (item) => {
        return `${item.addCar.driver.driverName} (${item.addCar.driver.driverMobile})`;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "کد بهداشتی حمل و نقل",
      selector: (item) => {
        return item?.trafficCode;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "نژاد",
      selector: (item) => {
        return item.poultryRequest.chickenBreed;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "تعداد",
      selector: (item) => item.quantity?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "وزن بار",
      selector: (item) => item?.weightInfo?.weight?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "میانگین وزن",
      selector: (item) => item?.weightInfo?.indexWeight?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "مرغدار",
      selector: (item) =>
        `${item.poultryRequest?.poultry?.unitName} (${item.poultryRequest.poultry?.user?.mobile})`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "دامپزشک فارم",
      selector: (item) =>
        item?.vetFarm?.vet?.user?.fullname
          ? item?.vetFarm?.vet?.user?.fullname +
            `(${item?.vetFarm?.vet?.user?.mobile})`
          : "فاقد دامپزشک",
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "کد رهگیری قرنطینه",
      selector: (item) => (item?.clearanceCode ? item?.clearanceCode : "-"),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "محل کشتار",
      selector: (item) => item.killPlace,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "شهر",
      selector: (item) => item.poultryRequest.poultry.address.city.name,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "تاریخ کشتار",
      selector: (item) =>
        item?.poultryRequest.sendDate
          ? format(new Date(item?.poultryRequest.sendDate), "yyyy/MM/dd")
          : "-",
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "کد سفارش کشتار",
      selector: (item) => item?.poultryRequest.orderCode,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "وضعیت",
      selector: (item) =>
        item.vetState === "accepted" ? "تایید تخلیه" : "در انتظار تخلیه",
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
  ];

  return (
    <Grid>
      <Grid
        container
        alignItems="center"
        justifyContent="space-between"
        gap={2}
        paddingTop={2}
        mb={1}
        width="100%"
      >
        <Typography>بارها </Typography>

        <Grid
          container
          gap={1}
          style={{
            borderStyle: "solid",
            borderWidth: "1px",
            padding: "5px",
            borderRadius: "15px",
            borderColor: "gray",
            justifyContent: "left",
          }}
          alignItems="center"
        >
          <Checkbox
            icon={<ToggleOffOutlinedIcon />}
            checkedIcon={<ToggleOnIcon />}
            checked={withDate}
            onChange={() => setWithDate(!withDate)}
            color="primary"
            size="large"
          />
          <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>
        <Grid container alignItems="center" gap={SPACING.SMALL}>
          <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>
        </Grid>
        <Tooltip title="خروجی اکسل">
          {/* <a
    href={`${axios.defaults.baseURL}hatching_report_from_age_excel/?age1=${selectedAge1}&age2=${selectedAge2}`}
    rel="noreferrer"
  > */}
          <Button
            color="success"
            onClick={() => {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                severity: "success",
              });
              const link = `${axios.defaults.baseURL}kill_house_total_wage_excel_new/?date1=${selectedDate1}&date2=${selectedDate2}&role=KillHouse&search=filter&value=${textValue}&key=${userKey}`;
              window.location.href = link;
            }}
          >
            <RiFileExcel2Fill size={32} />
          </Button>
          {/* </a> */}
        </Tooltip>
      </Grid>
      {true === false && (
        <PageTable
          columns={columns}
          data={data}
          progressPending={loading}
          pagination
          paginationServer
          paginationTotalRows={totalRows}
          onChangeRowsPerPage={handlePerRowsChange}
          onChangePage={handlePageChange}
        />
      )}
    </Grid>
  );
};
