import { Button, TextField, Typography } from "@mui/material";
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 { AppContext } from "../../../../contexts/AppContext";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { RiSearchLine } from "react-icons/ri";

export const ProvincePaymentLiveChickenDetails = ({ killhouseKey, type }) => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  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 [textValue, setTextValue] = useState("");

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

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

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

    setLoading(false);
  };

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

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

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

    try {
      const response = await axios.get(
        `kill_house_free_bar_wage_total/?search=filter&value=${textValue}&kill_house_key=${killhouseKey}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&type=${type}`
      );
      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.killHouse?.killHouseOperator?.user?.fullname} (${item.killHouse?.killHouseOperator?.user?.mobile})`;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "نام فروشنده",
      selector: (item) => {
        return item?.poultryName;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "شهر",
      selector: (item) => {
        return item?.city;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "تعداد",
      selector: (item) => {
        return type === "live"
          ? item?.quantity.toLocaleString()
          : item?.numberOfCarcasses.toLocaleString();
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "وزن",
      selector: (item) => {
        return type === "live"
          ? item?.liveWeight.toLocaleString()
          : item?.weightOfCarcasses.toLocaleString();
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "مبلغ کل",
      selector: (item) => {
        return item?.totalAmount?.toLocaleString();
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
  ];

  return (
    <Grid>
      <PageTable
        title={
          <Grid
            container
            alignItems="center"
            justifyContent="space-between"
            gap={2}
            paddingTop={2}
            mb={1}
            width="100%"
          >
            <Typography>
              بارهای {type === "live" ? "مرغ زنده" : "لاشه"}
            </Typography>

            <Grid>
              <DatePicker
                label="از تاریخ"
                id="date"
                renderInput={(params) => (
                  <TextField style={{ width: "160px" }} {...params} />
                )}
                value={selectedDate1}
                onChange={(e) => {
                  setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </Grid>
            <Grid>
              <DatePicker
                label="تا تاریخ"
                id="date"
                renderInput={(params) => (
                  <TextField style={{ width: "160px" }} {...params} />
                )}
                value={selectedDate2}
                onChange={(e) => {
                  setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </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>
          </Grid>
        }
        columns={columns}
        data={data}
        progressPending={loading}
        pagination
        paginationServer
        paginationTotalRows={totalRows}
        onChangeRowsPerPage={handlePerRowsChange}
        onChangePage={handlePageChange}
      />
    </Grid>
  );
};
