import {
  Button,
  Checkbox,
  FormControlLabel,
  Pagination,
  TextField,
  Tooltip,
  tooltipClasses,
  Typography,
} from "@mui/material";
import axios from "axios";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { PageTable } from "../../../../components/page-table/PageTable";
import { SPACING } from "../../../../data/spacing";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { formatJustDate } from "../../../../utils/formatTime";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import KeyboardDoubleArrowUpIcon from "@mui/icons-material/KeyboardDoubleArrowUp";
import KeyboardDoubleArrowDownIcon from "@mui/icons-material/KeyboardDoubleArrowDown";
import styled from "styled-components";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { SlaughterUnpaidFeesDetails } from "../slaughter-unpaid-fees-details/SlaughterUnpaidFeesDetails";
import { ProvinceArchiveFeeDetails } from "../../../province/components/province-archive-fee-details/ProvinceArchiveFeeDetails";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import BoxList from "../../../../components/box-list/BoxList";
import moment from "moment";
import { AppContext } from "../../../../contexts/AppContext";
import { DatePicker } from "@mui/x-date-pickers";

export const SlaughterArchivedFees = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [withDate, setWithDate] = useState(false);

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

  const dispatch = useDispatch();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const userInfo = useSelector((state) => state.userSlice);
  const [dataTableM, setDataTableM] = useState([]);

  const [textValue, setTextValue] = useState("");

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

  const fetchApiData = async (page, textValue) => {
    setLoading(true);
    const response = await axios.get(
      `province_wage/?search=filter&value=${textValue}&page=${page}&page_size=${perPage}&type=archive&role=${getRoleFromUrl()}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }`
    );
    setData(response.data.results);
    setTotalRows(response.data.count);
    setLoading(false);
    dispatch(LOADING_END());
  };

  const [page, setPage] = useState(0);
  const handleChangePageM = (event, newPage) => {
    dispatch(LOADING_START());
    setPage(newPage);
    fetchApiData(newPage + 1, textValue);
  };

  const handlePageChange = (page) => {
    fetchApiData(page, textValue);
  };

  const handlePerRowsChange = async (newPerPage, page) => {
    setLoading(true);
    const response = await axios.get(
      `province_wage/?search=filter&value=${textValue}&page=${page}&page_size=${newPerPage}&type=archive&role=${getRoleFromUrl()}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }`
    );

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

    setLoading(false);
  };

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

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

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

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

  const updateTable = () => {
    fetchApiData(1);
  };

  const columns = [
    {
      name: "کدسفارش",
      selector: (item) => item?.provinceRequest?.orderCode,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "مرغدار (تلفن)",
      selector: (item) =>
        `${item?.provinceRequest?.poultryFullname} (${item?.provinceRequest?.poultryMobile})`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "شهر",
      selector: (item) => `${item?.provinceRequest?.poultryCity}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "تاریخ کشتار",
      selector: (item) => formatJustDate(item?.provinceRequest?.sendDate),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "محل کشتار",
      selector: (item) => item?.provinceRequest?.killPlace,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "نژاد",
      selector: (item) => item?.provinceRequest?.breed,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "تعداد (قطعه)",
      selector: (item) =>
        item?.provinceRequest?.provinceKillRequestQuantity?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "وزن (کیلوگرم)",
      selector: (item) =>
        item?.provinceRequest?.provinceKillRequestTotalWeight?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "میانگین وزنی (کیلوگرم)",
      selector: (item) => item?.provinceRequest?.indexWeight,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "تعرفه  اتحادیه (ریال)",
      selector: (item) => item?.provinceRequest?.wage?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "مبلغ کل تعرفه  (ریال)",
      selector: (item) => (
        <ProvinceUnpaidFeeView item={item} updateTable={updateTable} />
      ),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "جزییات سفارش",
      selector: (item) => (
        <Button
          onClick={() => {
            dispatch(
              DRAWER({
                top: true,
                title: "جزییات سفارش",
                content: <SlaughterUnpaidFeesDetails item={item} />,
              })
            );
          }}
        >
          مشاهده
        </Button>
      ),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "اطلاعات بایگانی",
      selector: (item) => (
        <Button
          onClick={() => {
            dispatch(
              OPEN_MODAL({
                title: "اطلاعات بایگانی",
                content: <ProvinceArchiveFeeDetails item={item} />,
              })
            );
          }}
        >
          مشاهده
        </Button>
      ),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
  ];

  const tableTitle = (
    <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" // Change the color to your preference
                />
              }
            />
          </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_wage_archive_excel/?key=${userInfo?.userProfile?.key}${
              withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
            }`}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>
    </Grid>
  );

  const isMobile = window.innerWidth <= 600;

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        item?.provinceRequest?.orderCode,
        `${item?.provinceRequest?.poultryFullname} (${item?.provinceRequest?.poultryMobile})`,
        `${item?.provinceRequest?.poultryCity}`,
        <ProvinceUnpaidFeeView key={i} item={item} updateTable={updateTable} />,
        <Button
          key={i}
          onClick={() => {
            dispatch(
              DRAWER({
                top: true,
                title: "جزییات سفارش",
                content: <SlaughterUnpaidFeesDetails item={item} />,
              })
            );
          }}
        >
          مشاهده
        </Button>,
        <Button
          key={i}
          onClick={() => {
            dispatch(
              OPEN_MODAL({
                title: "اطلاعات بایگانی",
                content: <ProvinceArchiveFeeDetails item={item} />,
              })
            );
          }}
        >
          مشاهده
        </Button>,
      ];
    });

    setDataTableM(d);
  }, [data]);

  return (
    <Grid>
      {isMobile ? (
        <Grid container justifyContent="center" gap={SPACING.SMALL}>
          {tableTitle}
          <BoxList
            columns={[
              "عملیات",
              "ردیف",
              "نام فارم",
              "مرغدار",
              "شهر/تعاونی",
              "تاریخ جوجه ریزی",
              "نژاد",
              "سن",
              "تعداد جوجه ریزی",
              "مانده در سالن",
            ]}
            data={dataTableM}
          />
          <Pagination
            count={Math.ceil(totalRows / 10)}
            page={page + 1}
            variant="outlined"
            onChange={(event, newPage) => {
              handleChangePageM(event, newPage - 1);
            }}
          />
        </Grid>
      ) : (
        <PageTable
          title={tableTitle}
          columns={columns}
          data={data}
          progressPending={loading}
          pagination
          paginationServer
          paginationTotalRows={totalRows}
          onChangeRowsPerPage={handlePerRowsChange}
          onChangePage={handlePageChange}
        />
      )}
    </Grid>
  );
};

const ProvinceUnpaidFeeView = ({ item, updateTable }) => {
  const isBigger =
    item?.provinceRequest.prevTotalAmount < item?.provinceRequest.totalAmount;
  const isSmaller =
    item?.provinceRequest.prevTotalAmount > item?.provinceRequest.totalAmount;

  const prevTotalAmount = (
    <Grid container direction="column">
      <Grid>{isBigger && "افزایش یافته"}</Grid>
      <Grid>{isSmaller && "کاهش یافته"}</Grid>
      <Grid>
        مبلغ اولیه: {item?.provinceRequest?.prevTotalAmount?.toLocaleString()} ﷼
      </Grid>
      <Grid>ویرایش کننده: {item?.totalAmountEditor?.fullname}</Grid>
      <Grid>تاریخ ویرایش: {formatJustDate(item?.totalAmountEditor?.date)}</Grid>
      <Grid>سمت: {getFaUserRole(item?.totalAmountEditor?.role)}</Grid>
      <Grid>تلفن: {item?.totalAmountEditor?.mobile}</Grid>
    </Grid>
  );
  return (
    <Grid container alignItems="center" direction="column">
      {Boolean(item?.provinceRequest?.prevTotalAmount) && isBigger && (
        <Grid container alignItems="center">
          <KeyboardDoubleArrowUpIcon style={{ color: "red" }} />
          <HtmlTooltip title={prevTotalAmount}>
            <Typography style={{ color: "red" }} variant="caption">
              {item?.provinceRequest?.totalAmount?.toLocaleString()}
            </Typography>
          </HtmlTooltip>
        </Grid>
      )}

      {Boolean(item?.provinceRequest?.prevTotalAmount) && isSmaller && (
        <Grid container alignItems="center">
          <KeyboardDoubleArrowDownIcon style={{ color: "green" }} />
          <Tooltip title={prevTotalAmount}>
            <Typography style={{ color: "green" }} variant="caption">
              {item?.provinceRequest?.totalAmount?.toLocaleString()}
            </Typography>
          </Tooltip>
        </Grid>
      )}

      {!item?.provinceRequest?.prevTotalAmount && (
        <Typography color={"success"} variant="caption">
          {item?.provinceRequest?.totalAmount?.toLocaleString()}
        </Typography>
      )}
    </Grid>
  );
};

const HtmlTooltip = styled(({ className, ...props }) => (
  <Tooltip {...props} classes={{ popper: className }} />
))(({ theme }) => ({
  [`& .${tooltipClasses.tooltip}`]: {
    backgroundColor: "#f5f5f9",
    color: "rgba(0, 0, 0, 0.87)",
    maxWidth: 220,
    border: "1px solid #dadde9",
  },
}));
