import React, { useContext, useEffect, useState } from "react";
import {
  Button,
  Checkbox,
  FormControl,
  FormControlLabel,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Tooltip,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useDispatch } from "react-redux";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { formatTime } from "../../../../utils/formatTime";

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

  const [transactionType, setTransactionType] = useState("all");

  const handleChange = (event) => {
    setTransactionType(event.target.value);
  };

  const dispatch = useDispatch();
  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(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) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `live-stock-transactions/?search=filter&value=${textValue}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }&page=${page}&page_size=${perPage}&cooperative_key=${cooperative_key}&state=${transactionType}&name=${
        product?.key
      }`
    );
    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 updateTable = () => {
  //     fetchApiData(page !== 0 ? page : 1);
  //   };

  const convertToJson = (data) => {
    if (data) {
      return JSON.parse(data);
    }
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      const products = item?.products?.map((option, index) => {
        return [
          index + 1,
          option?.name,
          option?.curWeight?.toLocaleString(),
          option?.price?.toLocaleString(),
          option?.curPrice?.toLocaleString(),
        ];
      });

      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        formatTime(item?.date),
        item?.fullname || "-",
        item?.natcode || "-",
        item?.mobile || "-",
        `${item?.pos?.cooperative?.name} شهرستان ${item?.pos?.cooperative?.user?.cityName} (${item?.pos?.cooperative?.user?.fullname})`,
        item?.pos?.cooperative?.user?.mobile,
        item?.paid ? "پرداخت شده" : `پرداخت نشده (${item?.result})`,
        convertToJson(item?.additional).isTaavoni ? "تعاونی" : "کارخانه",
        item?.products
          ? item?.products.map((option) => option.name).join("-")
          : "-",
        convertToJson(item?.additional)?.ownerNatcode?.toLocaleString() || 0,
        convertToJson(item?.additional)?.cur_heavy?.toLocaleString() || 0,
        convertToJson(item?.additional)?.cur_light?.toLocaleString() || 0,
        item?.products
          .reduce(
            (accumulator, currentValue) =>
              accumulator + currentValue?.curWeight,
            0
          )
          .toLocaleString(),
        item?.price?.toLocaleString(),
        convertToJson(item?.additional)?.cooperative_price?.toLocaleString() ||
          0,
        convertToJson(item?.additional)?.union_price?.toLocaleString() || 0,
        <Button
          size="small"
          variant="outlined"
          key={i}
          onClick={() => {
            dispatch(
              OPEN_MODAL({
                title: "جزئیات محصول",
                content: (
                  <Grid container xs={12} justifyContent="center">
                    <SimpleTable
                      columns={["ردیف", "محصول", "وزن", "فی", "قیمت کل"]}
                      data={products}
                    />
                  </Grid>
                ),
              })
            );
          }}
        >
          مشاهده
        </Button>,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `live-stock-transactions/?search=filter&value=${textValue}${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }&page=${1}&page_size=${perPage}&cooperative_key=${cooperative_key}&state=${transactionType}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Grid width="200px">
          <FormControl size="small">
            <InputLabel id="demo-simple-select-label">فیلتر تراکنش</InputLabel>
            <Select
              labelId="demo-simple-select-label"
              id="demo-simple-select"
              value={transactionType}
              label="Age"
              onChange={handleChange}
            >
              <MenuItem value={"all"}>همه</MenuItem>
              <MenuItem value={"paid"}>تراکنش های موفق</MenuItem>
              <MenuItem value={"unpaid"}>تراکنش های ناموفق</MenuItem>
            </Select>
          </FormControl>
        </Grid>

        <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>
        <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>
        <Tooltip title="خروجی اکسل">
          <a href={`${axios.defaults.baseURL}`} rel="noreferrer">
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>

      <ResponsiveTable
        ignoreTextsLength
        data={tableData}
        columns={[
          "ردیف",
          "تاریخ",
          "خریدار",
          "کد ملی خریدار",
          "موبایل خریدار",
          "فروشنده",
          "تلفن فروشنده",
          "وضعیت",
          "محل تحویل",
          "کالا",
          "کد ملی فروشنده",
          "دام سنگین",
          "دام سبک",
          "وزن (کیلوگرم)",
          "مبلغ تراکنش",
          "سهم تعاونی",
          "سهم اتحادیه",
          "جزئیات محصولات",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title={`تراکنش های ${product?.label}`}
      />
    </Grid>
  );
};
