import {
  Button,
  TextField,
  Tooltip,
  tooltipClasses,
  Typography,
} from "@mui/material";
import axios from "axios";
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { PageTable } from "../../../../components/page-table/PageTable";
import { SPACING } from "../../../../data/spacing";
import { DRAWER, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { formatJustDate } from "../../../../utils/formatTime";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { SlaughterUnpaidFeesDetails } from "../../../slaughter-house/components/slaughter-unpaid-fees-details/SlaughterUnpaidFeesDetails";
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 { ProvinceArchiveFeeDetails } from "../province-archive-fee-details/ProvinceArchiveFeeDetails";
import { IconButton } from "@mui/material";
import Visibility from "@mui/icons-material/Visibility";
import Unarchive from "@mui/icons-material/Unarchive";
import { ProvinceUnarchiveFee } from "../province-unarchive-fee/ProvinceUnarchiveFee";
import { RiSearchLine } from "react-icons/ri";

export const ProvinceKillhouseArchiveFee = ({ killhouseKey }) => {
  const dispatch = useDispatch();
  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(
      `province_wage/?search=filter&value=${textValue}&page=${page}&page_size=${perPage}&type=archive&kill_house_key=${killhouseKey}&role=${getRoleFromUrl()}`
    );
    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(
      `province_wage/?search=filter&value=${textValue}&page=${page}&page_size=${newPerPage}&type=archive&kill_house_key=${killhouseKey}&role=${getRoleFromUrl()}`
    );

    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(
        `province_wage/?search=filter&value=${textValue}&type=archive&kill_house_key=${killhouseKey}&role=${getRoleFromUrl()}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  };

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

  let 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) => (
        <IconButton
          color="primary"
          onClick={() => {
            dispatch(
              DRAWER({
                top: true,
                title: "جزییات سفارش",
                content: <SlaughterUnpaidFeesDetails item={item} />,
              })
            );
          }}
        >
          <Visibility />
        </IconButton>
      ),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "90px",
    },
    {
      name: "اطلاعات بایگانی",
      selector: (item) => (
        <IconButton
          color="primary"
          onClick={() => {
            dispatch(
              OPEN_MODAL({
                title: "اطلاعات بایگانی",
                content: <ProvinceArchiveFeeDetails item={item} />,
              })
            );
          }}
        >
          <Visibility />
        </IconButton>
      ),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "90px",
    },
    {
      name: "خارج کردن از بایگانی",
      selector: (item) => {
        return (
          <IconButton
            color="primary"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "آیا مطمئن هستید؟",
                  content: (
                    <ProvinceUnarchiveFee
                      updateTable={updateTable}
                      provinceKillRequestKey={
                        item.provinceRequest.provinceKillRequestKey
                      }
                    />
                  ),
                })
              );
            }}
          >
            <Unarchive />
          </IconButton>
        );
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "90px",
    },
  ];

  if (getRoleFromUrl() === "KillHouse") {
    columns.pop();
  }

  return (
    <Grid>
      <Typography>
        تعرفه های معوقه{" "}
        {data[0]?.provinceRequest?.killHouseUserFullName &&
          `${data[0]?.provinceRequest?.killer ? "کشتارکن" : "کشتارگاه"} ${
            data[0]?.provinceRequest?.killHouseUserFullName
          }`}
      </Typography>
      <PageTable
        title={
          <Grid
            container
            alignItems="center"
            justifyContent="space-between"
            gap={2}
            paddingTop={2}
            mb={1}
            width="100%"
          >
            <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>
  );
};

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",
  },
}));
