import { useContext, useEffect, useState } from "react";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Grid } from "../../../../components/grid/Grid";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import { useDispatch } from "react-redux";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import axios from "axios";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import PdfKillRequest from "../province-settlement-pdf-kill-request/ProvinceSettlementPdfKillRequest";
import {
  Button,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  TextField,
} from "@mui/material";
import {
  provinceTradePanelMarketRequestAdminOverview,
  provinceTradePanelMarketRequestOverview,
} from "../../services/province-trade-panel-market-request-overview";
import { SPACING } from "../../../../data/spacing";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { AppContext } from "../../../../contexts/AppContext";
import { RiSearchLine } from "react-icons/ri";
import { ProvinceTradePanelOldRequests } from "../province-trade-panel-old-requests/ProvinceTradePanelOldRequests";

export const ProvinceTradePanelMarketOldRequest = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  const [overViewSelectedDate1, setOverviewSelectedDate1] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );
  const [overViewSelectedDate2, setOverviewSelectedDate2] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );

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

  const dispatch = useDispatch();
  const [data, setData] = useState([]);
  const [filter, setFilter] = useState("pending");
  const [tableData, setTableData] = useState([]);
  const [overViewData, setOverViewData] = useState([]);
  const [overViewDataList, setOverViewDataList] = useState([]);
  const [overViewDataDashboard, setOverViewDataDashboard] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [page, setPage] = useState(1);

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

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

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

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const [textValueOverview, setTextValueOverView] = useState("");

  const handleTextChangeOverView = (event) => {
    setTextValueOverView(event.target.value);
  };

  const getOverviewData = (event) => {
    if (event) {
      event.preventDefault();
    }
    dispatch(
      provinceTradePanelMarketRequestAdminOverview({
        date1: overViewSelectedDate1,
        date2: overViewSelectedDate2,
        search: "filter",
        value: textValueOverview,
      })
    ).then((r) => {
      setOverViewDataDashboard(r.payload.data);
    });
    dispatch(
      provinceTradePanelMarketRequestOverview({
        date1: overViewSelectedDate1,
        date2: overViewSelectedDate2,
        search: "filter",
        value: textValueOverview,
      })
    ).then((r) => {
      setOverViewData(r.payload.data);
    });
  };

  const fetchApiData = async (pageNumber = page, event) => {
    if (event) {
      event.preventDefault();
    }
    try {
      dispatch(LOADING_START());
      const response = await axios.get(
        `/market-requests/?role=${getRoleFromUrl()}&search=filter&value=&page=${pageNumber}&page_size=${perPage}&type=${filter}&date1=${selectedDate1}&date2=${selectedDate2}&search=filter&value=${
          textValue ? textValue : ""
        }`
      );

      dispatch(LOADING_END());
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      dispatch(LOADING_END());
    }
  };

  const handleUpdate = () => {
    fetchApiData(1);
    getOverviewData();
  };

  // Helper function to parse marketStateMessage JSON string
  const parseMarketStateMessage = (messageString) => {
    if (!messageString || typeof messageString !== "string") {
      return null;
    }

    try {
      // Remove outer quotes if present and replace single quotes with double quotes for valid JSON
      let jsonString = messageString.trim();
      // Remove outer single or double quotes
      if (
        (jsonString.startsWith("'") && jsonString.endsWith("'")) ||
        (jsonString.startsWith('"') && jsonString.endsWith('"'))
      ) {
        jsonString = jsonString.slice(1, -1);
      }
      // Replace single quotes with double quotes
      jsonString = jsonString.replace(/'/g, '"');
      const parsed = JSON.parse(jsonString);
      return {
        fullname: parsed?.fullname || "",
        mobile: parsed?.mobile || "",
        date: parsed?.date || "",
      };
    } catch (error) {
      console.error("Error parsing marketStateMessage:", error);
      return null;
    }
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      // Parse marketStateMessage if it exists
      const marketStateInfo = parseMarketStateMessage(item?.marketStateMessage);
      const statusText = `${
        item?.marketState === "deleted"
          ? "حذف شده"
          : item?.marketCodeStatus === true &&
            item?.marketFinalAccept === true &&
            !item?.inputMarketCode &&
            item?.marketState === "pending"
          ? "در انتظار ورود کد احراز"
          : item?.marketFinalAccept === false
          ? "در انتظار تایید خریدار"
          : item?.marketState === "pending"
          ? "در انتظار تایید استان"
          : item?.marketState === "accepted"
          ? "تایید شده"
          : item?.marketState === "rejected"
          ? "رد شده"
          : item?.marketState === "deleted"
          ? "حذف شده"
          : ""
      }`;

      // Build status display with marketStateMessage info if available
      // Only show marketStateMessage info when market_state === "deleted"
      const isDeleted = item?.marketState === "deleted";
      const hasMarketStateMessage =
        item?.marketStateMessage &&
        item.marketStateMessage !== null &&
        item.marketStateMessage !== "";

      const statusDisplay =
        isDeleted && marketStateInfo
          ? `${statusText}${statusText ? " " : ""}( ${
              marketStateInfo.fullname
            } ${marketStateInfo.mobile}) - ${formatTime(marketStateInfo.date)}`
          : isDeleted && !hasMarketStateMessage
          ? `${statusText}${statusText ? " " : ""}(سیستمی)`
          : statusText;

      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        `${item?.poultry?.unitName || ""}`,
        `${item?.poultry?.fullname || ""} (${item?.poultry?.mobile || ""})`,
        item?.poultry?.city || "",
        ...(getRoleFromUrl() !== "KillHouse"
          ? [
              `${item?.killHouse?.killer === true ? "کشتارکن" : "کشتارگاه"} ${
                item?.killHouse?.name || ""
              }`,
              `${item?.killHouse?.fullname || ""} (${
                item?.killHouse?.mobile || ""
              })`,
              item?.killHouse?.city || "",
            ]
          : []),
        item?.chickenBreed || "",
        item?.poultryRequest?.killingAge?.toLocaleString() || "0",
        item?.killCapacity?.toLocaleString() || "0",
        formatJustDate(item?.reciveDate) || "-",
        item?.createDate ? formatTime(item.createDate) : "-",
        item?.IndexWeight || 0,
        Math.round(
          item?.IndexWeight * item?.killCapacity || 0
        ).toLocaleString(),
        item?.amount ? item.amount.toLocaleString() : "0",
        item?.paymentDeadlineDate
          ? formatJustDate(item.paymentDeadlineDate)
          : "-",
        statusDisplay,
        item?.marketState === "accepted" ? (
          <PdfKillRequest pdf_key={item?.key} />
        ) : (
          "-"
        ),
      ];
    });

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

  useEffect(() => {
    handleUpdate();
  }, [perPage, filter, selectedDate1, selectedDate2]);

  useEffect(() => {
    getOverviewData();
  }, [overViewSelectedDate1, overViewSelectedDate2]);

  useEffect(() => {
    if (overViewData) {
      const d = overViewData?.map((item, i) => {
        return [
          i + 1,
          item?.name,
          item?.info?.killHouseTodayShare?.toLocaleString() || "0",
          item?.info?.killHouseMarketKillRequestsQuantity?.toLocaleString() ||
            "0",
          item?.info?.killHouseMarketKillRequestsQuantityFirst?.toLocaleString() ||
            "0",
          item?.info?.killHouseMarketKillRequestsQuantityFinal?.toLocaleString() ||
            "0",
          item?.info?.killHouseMarketKillRequestsQuantityWeight?.toLocaleString() ||
            "0",
          item?.info?.killHouseMarketKillRequestsQuantityFirstWeight?.toLocaleString() ||
            "0",
          item?.info?.killHouseMarketKillRequestsQuantityFinalWeight?.toLocaleString() ||
            "0",
          item?.info?.totalKillHouseMarketKillRequestsQuantityAgreementLightWeight?.toLocaleString() ||
            "0",
          item?.info?.totalKillHouseMarketKillRequestsQuantityLightWeight?.toLocaleString() ||
            "0",
          item?.info?.totalKillHouseMarketKillRequestsQuantityHeavyWeight?.toLocaleString() ||
            "0",
          item?.info?.killHouseTodayLeftShare?.toLocaleString() || "0",
          item?.info?.marketLightShare?.toLocaleString() || "0",
        ];
      });

      setOverViewDataList(d);
    }
  }, [overViewData]);

  return (
    <Grid container mt={2}>
      <Grid container gap={SPACING.SMALL}>
        <Grid>
          <FormControl>
            <InputLabel id="demo-simple-select-label">فیلتر نتایج</InputLabel>
            <Select
              sx={{ minWidth: "120px" }}
              size="small"
              labelId="demo-simple-select-label"
              id="demo-simple-select"
              value={filter}
              onChange={(event) => setFilter(event.target.value)}
              label="Age"
              // onChange={handleChange}
            >
              <MenuItem value={"pending"}>در انتظار</MenuItem>
              <MenuItem value={"accepted"}>تایید شده</MenuItem>
              <MenuItem value={"rejected"}>رد شده</MenuItem>
              <MenuItem value={"deleted"}>حذف شده</MenuItem>
              <MenuItem value={"all"}>همه سفارشات</MenuItem>
            </Select>
          </FormControl>
        </Grid>
        <Grid>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} size="small" {...params} />
            )}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} size="small" {...params} />
            )}
            value={selectedDate2}
            onChange={(e) => {
              setSelectedDate2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <form
          onSubmit={(e) => {
            fetchApiData(1, e);
          }}
        >
          <TextField
            id="outlined-basic"
            size="small"
            label="جستجو"
            variant="outlined"
            style={{ width: 250 }}
            onChange={handleTextChange}
          />
          <Button
            // disabled={!textValue}
            type="submit"
            onSubmit={(e) => {
              fetchApiData(1, e);
            }}
            endIcon={<RiSearchLine />}
          >
            جستجو
          </Button>
        </form>
      </Grid>

      <ResponsiveTable
        title={"معاملات گذشته"}
        customWidth="100%"
        data={tableData}
        columns={[
          "ردیف",
          "فارم",
          "مرغدار",
          "شهر",
          "ماهیت خریدار",
          "خریدار",
          "آدرس خریدار",
          "نژاد",
          "سن (روز)",
          "تعداد قطعه",
          "تاریخ کشتار",
          "تاریخ ثبت سفارش",
          "میانگین وزنی (کیلوگرم)",
          "وزن تقریبی (کیلوگرم)",
          "مبلغ هر کیلو (ریال)",
          "حداکثر مهلت تسویه",
          "وضعیت",
          "توافق نامه",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        customColors={[{ rest: true, color: "green" }]}
      />

      <Grid container gap={SPACING.SMALL}>
        <Grid>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} size="small" {...params} />
            )}
            value={overViewSelectedDate1}
            onChange={(e) => {
              setOverviewSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} size="small" {...params} />
            )}
            value={overViewSelectedDate2}
            onChange={(e) => {
              setOverviewSelectedDate2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>

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

      <Grid container xs={12} mt={2} gap={2}>
        <ResponsiveTable
          isDashboard
          title="خلاصه معاملات"
          customWidth="100%"
          data={[
            [
              overViewDataDashboard?.totalPoultryRequestsQuantity?.toLocaleString() ||
                "0",
              overViewDataDashboard?.killHouseTodayShare?.toLocaleString() ||
                "0",
              overViewDataDashboard?.killHouseMarketKillRequestsQuantity?.toLocaleString() ||
                "0",
              overViewDataDashboard?.killHouseMarketKillRequestsQuantityFirst?.toLocaleString() ||
                "0",
              overViewDataDashboard?.killHouseMarketKillRequestsQuantityFinal?.toLocaleString() ||
                "0",
              overViewDataDashboard?.killHouseMarketKillRequestsQuantityWeight?.toLocaleString() ||
                "0",
              overViewDataDashboard?.killHouseMarketKillRequestsQuantityFirstWeight?.toLocaleString() ||
                "0",
              overViewDataDashboard?.killHouseMarketKillRequestsQuantityFinalWeight?.toLocaleString() ||
                "0",
              overViewDataDashboard?.totalKillHouseMarketKillRequestsQuantityAgreementLightWeight?.toLocaleString() ||
                "0",
              overViewDataDashboard?.totalKillHouseMarketKillRequestsQuantityLightWeight?.toLocaleString() ||
                "0",
              overViewDataDashboard?.totalKillHouseMarketKillRequestsQuantityHeavyWeight?.toLocaleString() ||
                "0",
              overViewDataDashboard?.killHouseTodayLeftShare?.toLocaleString() ||
                "0",
              overViewDataDashboard?.marketLightShare?.toLocaleString() || "0",
            ],
          ]}
          noPagination
          columns={[
            "حجم کل سفارشات (قطعه)",
            "سهمیه روز (قطعه)",
            "کل حجم خریداری شده (قطعه)",
            "حجم خرید موقت (قطعه)",
            "حجم خرید نهایی (قطعه)",
            "کل وزن خریداری شده (کیلوگرم)",
            "وزن خرید موقت (کیلوگرم)",
            "وزن خرید نهایی (کیلوگرم)",
            "حجم خرید سبک توافقی (قطعه)",
            "حجم خرید سبک (قطعه)",
            "حجم خرید سنگین (قطعه)",
            "مانده سهمیه (قطعه)",
            "الزام به خرید سبک (قطعه)",
          ]}
        />

        <ResponsiveTable
          title="گزارش معاملات"
          customWidth="100%"
          data={overViewDataList}
          paginated
          columns={[
            "ردیف",
            "کشتارگاه",
            "سهمیه روز",
            "کل حجم خریداری شده (قطعه)",
            "حجم خرید موقت (قطعه)",
            "حجم خرید نهایی (قطعه)",
            "کل وزن خریداری شده (کیلوگرم)",
            "وزن خرید موقت (کیلوگرم)",
            "وزن خرید نهایی (کیلوگرم)",
            "حجم خرید سبک توافقی (قطعه)",
            "حجم خرید سبک (قطعه)",
            "حجم خرید سنگین (قطعه)",
            "مانده سهمیه (قطعه)",
            "الزام به خرید سبک (قطعه)",
          ]}
        />
      </Grid>

      <ProvinceTradePanelOldRequests />
    </Grid>
  );
};
