import React, { useContext, useEffect, useState } from "react";
import {
  Box,
  Button,
  Card,
  CardContent,
  IconButton,
  TextField,
  Typography,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { AppContext } from "../../../../contexts/AppContext";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Grid } from "../../../../components/grid/Grid";
import { ProvinceAllocateOperations } from "../province-allocate-operations/ProvinceAllocateOperations";
import { ProvinceEditSendDate } from "../province-edit-send-date/ProvinceEditSendDate";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import EditIcon from "@mui/icons-material/Edit";
import { getPoultryRequestsTotalQuantityService } from "../../../city/services/get-poultry-requests-total-quantity";
import { motion } from "framer-motion";
import { RiSearchLine } from "react-icons/ri";

const cardVariants = {
  hidden: { opacity: 0, y: 20 },
  visible: { opacity: 1, y: 0 },
};

export const ProvinceAllocateRequests = () => {
  const [, , selectedDate1, setSelectedDate1] = useContext(AppContext);

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

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

  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);

  const fetchApiData = async (page) => {
    dispatch(getPoultryRequestsTotalQuantityService(selectedDate1)).then(
      async () => {
        dispatch(LOADING_START());
        const response = await axios.get(
          `city_operator_check_request_new/?state=waiting&date=${selectedDate1}&page=${page}&page_size=${perPage}&search=filter&value=${
            textValue ? textValue : ""
          }`
        );
        dispatch(LOADING_END());
        setData(response.data.results);
        setTotalRows(response.data.count);
      }
    );
  };

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

  const getItemFreeSaleInProvince = (item) => {
    let sellType = "";
    if (item?.poultryRequest?.freeSaleInProvince) {
      sellType = "آزاد";
    } else {
      sellType = "دولتی";
    }
    return sellType;
  };

  const updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.poultryRequest?.orderCode,
        getItemFreeSaleInProvince(item),
        formatTime(item?.poultryRequest?.createDate),
        <Grid
          key={item?.poultryRequest?.orderCode}
          container
          alignItems="center"
          justifyContent="center"
          width="100px"
        >
          <Typography variant="caption">
            {formatJustDate(item?.poultryRequest?.sendDate)}
          </Typography>
          <IconButton
            size={"small"}
            color="primary"
            disabled={Number(item?.quantity?.allocatedNumber) > 0}
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "ویرایش تاریخ درخواست کشتار",
                  content: (
                    <ProvinceEditSendDate
                      poultryRequestKey={item?.poultryRequest?.key}
                    />
                  ),
                })
              );
            }}
          >
            <EditIcon fontSize="small" />
          </IconButton>
        </Grid>,
        item?.poultryRequest?.freezing
          ? "انجماد"
          : item?.poultryRequest?.export
          ? "صادرات"
          : "عادی",
        `${item?.poultryRequest?.process?.poultry?.poultryName}/${item?.poultryRequest?.process?.poultry?.poultryMobile}`,
        item?.poultryRequest?.killHouseList.length
          ? item?.poultryRequest?.killHouseList?.join(" - ")
          : "-",
        `${item?.poultryRequest?.process?.poultry?.poultryProvince}/${item?.poultryRequest?.process?.poultry?.poultryCity}`,
        item?.poultryRequest?.poultry?.cityOperator,
        item?.poultryRequest?.killingAge,
        item?.poultryRequest?.process?.poultry?.IndexWeight,
        item?.poultryRequest?.process?.poultry?.totalWeight?.toLocaleString(),
        item?.poultryRequest?.process?.poultry?.poultryQuantity?.toLocaleString(),
        item?.poultryRequest?.amount?.toLocaleString() + " ﷼",
        <Typography color="green" variant="caption" fontWeight="bold" key="sss">
          {item?.quantity?.allocatedNumber?.toLocaleString()}
        </Typography>,
        item?.quantity?.returnedNumber?.toLocaleString(),
        item?.quantity?.assignableNumber?.toLocaleString(),
        <ProvinceAllocateOperations
          key={i}
          remainQuantity={
            item?.poultryRequest?.process?.poultry?.poultryRemainQuantity
          }
          item={item}
          getItemFreeSaleInProvince={getItemFreeSaleInProvince}
          updateTable={updateTable}
        />,
      ];
    });

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

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `city_operator_check_request_new/?state=waiting&date=${selectedDate1}&page=${1}&page_size=${perPage}&search=filter&value=${
          textValue ? textValue : ""
        }`
      );

      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const { poultryRequestsTotalQuantity } = useSelector(
    (state) => state.citySlice
  );

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
        px={{
          xs: 2,
          sm: 0,
        }}
      >
        <Grid>
          <DatePicker
            label="تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} size="small" />
            )}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>

        <Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
      </Grid>

      <Grid
        container
        sx={{
          gap: {
            xs: "8px 0px",
            sm: "8px",
          },
        }}
        mt={2}
        justifyContent="center"
        alignItems="center"
      >
        {[
          {
            label: "تعداد درخواست کشتار",
            value: poultryRequestsTotalQuantity?.acceptedQuantity || 0,
          },
          {
            label: "اعلام نیاز کشتارگاه ها",
            value: poultryRequestsTotalQuantity?.killRequestsQuantity || 0,
          },
          {
            label: "تخصیص داده شده",
            value: poultryRequestsTotalQuantity?.allocatedQuantity || 0,
          },
          {
            label: "قابل تخصیص",
            value: poultryRequestsTotalQuantity?.assignableQuantity || 0,
          },
          {
            label: "برگشت داده شده",
            value: poultryRequestsTotalQuantity?.returnedQuantity || 0,
          },
        ].map((item, index) => (
          <Grid item sx={{ width: "250px" }} key={index}>
            <motion.div
              variants={cardVariants}
              initial="hidden"
              animate="visible"
              transition={{ duration: 0.5, delay: index * 0.2 }}
            >
              <Card elevation={3} sx={{ borderRadius: 2 }}>
                <CardContent>
                  <Typography color="red" variant="subtitle2" gutterBottom>
                    {item.label}
                  </Typography>
                  <Typography variant="h6" sx={{ fontSize: 18 }}>
                    {item.value?.toLocaleString()} قطعه
                  </Typography>
                </CardContent>
              </Card>
            </motion.div>
          </Grid>
        ))}
      </Grid>
      <Box
        sx={{
          width: "100%",
        }}
        px={{
          xs: 1,
          sm: 0,
        }}
      >
        <ResponsiveTable
          data={tableData}
          columns={[
            "ردیف",
            "کد سفارش",
            "نوع فروش",
            "تاریخ ثبت درخواست",
            "تاریخ کشتار",
            "نوع کشتار",
            "مرغدار/تلفن",
            "کشتارگاه انتخابی",
            "استان/شهر",
            "تعاونی",
            "سن مرغ",
            "میانگین وزنی",
            "وزن تقریبی",
            "تعداد",
            "قیمت مرغدار",
            "تخصیص داده شده",
            "برگشت داده شده",
            "قابل تخصیص",
            "عملیات",
          ]}
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
          title="مدیریت تخصیصات"
        />
      </Box>
    </Grid>
  );
};
