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 { formatJustDate } from "../../../../utils/formatTime";
import { RiSearchLine } from "react-icons/ri";

export const ProvincePaymentChainDetails = ({ 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(
      `chain-allocation-total-wage/?search=filter&value=${textValue}&page=${page}&page_size=${perPage}&type=paid&chain_company_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(
      `chain-allocation-total-wage/?search=filter&value=${textValue}&page=${page}&page_size=${newPerPage}&type=paid&chain_company_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]);

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

    try {
      const response = await axios.get(
        `chain-allocation-total-wage/?search=filter&value=${textValue}&type=paid&chain_company_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, i) => {
        return i + 1;
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "30px",
    },
    {
      name: "تاریخ ایجاد",
      selector: (item) => {
        return formatJustDate(item?.createDate);
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "auto",
    },
    {
      name: "مرغداری",
      selector: (item, i) => {
        return `${item?.poultryHatching?.poultry?.unitName} (${item?.poultryHatching?.poultry?.user?.mobile})`;
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "auto",
    },
    {
      name: "شرکت زنجیره",
      selector: (item, i) => {
        return `${item?.chainCompany?.name} (${item?.chainCompany?.user.mobile})`;
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "auto",
    },
    {
      name: "کد قرنطینه",
      selector: (item, i) => {
        return item?.quarantineCode ? item?.quarantineCode : "-";
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "auto",
    },
    {
      name: "تعداد",
      selector: (item) => {
        return item?.quantity;
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "auto",
    },
    {
      name: "وزن",
      selector: (item) => {
        return item?.weight;
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "60px",
    },
  ];

  return (
    <Grid>
      <PageTable
        title={
          <Grid
            container
            alignItems="center"
            justifyContent="space-between"
            gap={2}
            paddingTop={2}
            mb={1}
            width="100%"
          >
            <Typography>سفارشات زنجیره</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>
  );
};
