import axios from "axios";
import {
  Button,
  Checkbox,
  FormControlLabel,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
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 { ProvinceFeesTotalOverview } from "../province-fees-total-overview/ProvinceFeesTotalOverview";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { useSelector } from "react-redux";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

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

  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_total_wage/?search=filter&value=${textValue}&type=total&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_total_wage/?search=filter&value=${textValue}&type=total&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_total_wage/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&type=total${
          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?.toLocaleString()}`,
      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) => `${item?.info?.paidCount?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "90px",
    },
    {
      name: "تعداد قطعات پرداخت شده",
      selector: (item) => `${item?.info?.totalPaidQuantity?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "90px",
    },
    {
      name: "وزن قطعات پرداخت شده (کیلوگرم)",
      selector: (item) => `${item?.info?.totalWeightPaid?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "90px",
    },
    {
      name: "مبلغ قطعات پرداخت شده (﷼)",
      selector: (item) => `${item?.info?.totalPaidWage?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "90px",
    },
    {
      name: "تعداد سفارشات پرداخت نشده",
      selector: (item) => `${item?.info?.unpaidCount?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "90px",
    },
    {
      name: "تعداد قطعات پرداخت نشده",
      selector: (item) =>
        `${item?.info?.totalUnpaidQuantity?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "90px",
    },
    {
      name: "وزن قطعات پرداخت نشده (کیلوگرم)",
      selector: (item) => `${item?.info?.totalWeightUnpaid?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "90px",
    },
    {
      name: "مبلغ قطعات پرداخت نشده (﷼)",
      selector: (item) => `${item?.info?.totalUnpaidWage?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "90px",
    },
  ];

  return (
    <Grid container justifyContent="end">
      <ProvinceFeesTotalOverview />
      <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>اطلاعات کلی</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
                  }all_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>
  );
};
