import { useContext, useEffect, useState, useMemo, useCallback } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import axios from "axios";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Button, TextField, Tooltip } from "@mui/material";
import { VetFarmEditTrafficCode } from "../../../vet-farm/components/vet-farm-edit-traffic-code/VetFarmEditTrafficCode";
import { format } from "date-fns-jalali";
import { SlaughterNoneRecieptOperation } from "../slaughter-none-reciept-operation/SlaughterNoneRecieptOperation";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import moment from "moment";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { AppContext } from "../../../../contexts/AppContext";
import { DatePicker } from "@mui/x-date-pickers";
import ShowImage from "../../../../components/show-image/ShowImage";
import { formatJustDate } from "../../../../utils/formatTime";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

// Constants
const ROLES = {
  PROVINCE_OPERATOR: "ProvinceOperator",
  SUPER_ADMIN: "SuperAdmin",
  ADMIN_X: "AdminX",
  SUPPORTER: "Supporter",
  VET_SUPERVISOR: "VetSupervisor",
  VET_FARM: "VetFarm",
  CITY_VET: "CityVet",
};

const KILL_TYPES = {
  FREEZING: "انجماد",
  EXPORT: "صادرات",
  NORMAL: "عادی",
};

const SALE_TYPES = {
  FREE: "آزاد",
  GOVERNMENT: "دولتی",
};

const NON_RECEIPT_STATES = {
  ACCEPTED: "تایید شده",
  REJECTED: "رد شده",
  PENDING: "درانتظار تایید",
};

const DEFAULT_PER_PAGE = 10;
const DEFAULT_PAGE = 1;

// Helper functions
const formatDate = (date) => {
  if (!date) return "-";
  return format(new Date(date), "yyyy/MM/dd");
};

const formatCurrency = (value) => {
  return value ? `${value.toLocaleString()} ﷼` : "-";
};

const formatNumber = (value) => {
  return value ? value.toLocaleString() : "-";
};

const formatUserInfo = (name, mobile) => {
  return name && mobile ? `${name} (${mobile})` : "-";
};

const getKillType = (item) => {
  if (item?.poultryRequest?.freezing) return KILL_TYPES.FREEZING;
  if (item?.poultryRequest?.export) return KILL_TYPES.EXPORT;
  return KILL_TYPES.NORMAL;
};

const getSaleType = (item) => {
  return item?.poultryRequest?.freeSaleInProvince
    ? SALE_TYPES.FREE
    : SALE_TYPES.GOVERNMENT;
};

const getNonReceiptState = (item) => {
  if (item?.nonReceiptState === "accepted") return NON_RECEIPT_STATES.ACCEPTED;
  if (item?.nonReceiptState === "rejected") return NON_RECEIPT_STATES.REJECTED;
  return NON_RECEIPT_STATES.PENDING;
};

const formatCheckerInfo = (checker, mobile) => {
  return checker && mobile ? `${checker}(${mobile})` : "-";
};

const buildApiUrl = (params) => {
  const { textValue, role, date1, date2, page, perPage, roleKey } = params;
  const baseUrl = "non-receipt-request/";
  const queryParams = new URLSearchParams({
    search: "filter",
    value: textValue || "",
    role: role || "",
    date1: date1 || "",
    date2: date2 || "",
    page: page || DEFAULT_PAGE,
    page_size: perPage || DEFAULT_PER_PAGE,
  });

  if (roleKey) {
    queryParams.append("role_key", roleKey);
  }

  return `${baseUrl}?${queryParams.toString()}`;
};

const buildExcelUrl = (params) => {
  const { baseURL, role, roleKey, userKey, textValue, date1, date2 } = params;
  const queryParams = new URLSearchParams({
    role: role || "",
    key: userKey || "",
    search: "filter",
    value: textValue || "",
    date1: date1 || "",
    date2: date2 || "",
  });

  if (roleKey) {
    queryParams.append("role_key", roleKey);
  }

  return `${baseURL}non_receipt_request_excel/?${queryParams.toString()}`;
};

const isTrafficCodeEditable = (role, item) => {
  const adminRoles = [
    ROLES.PROVINCE_OPERATOR,
    ROLES.SUPER_ADMIN,
    ROLES.ADMIN_X,
    ROLES.SUPPORTER,
    ROLES.VET_SUPERVISOR,
  ];

  if (adminRoles.includes(role)) {
    return true;
  }

  const vetRoles = [ROLES.VET_FARM, ROLES.CITY_VET];
  return (
    item.trash !== true &&
    item.assignmentStateArchive === "pending" &&
    !item?.clearanceCode &&
    vetRoles.includes(role)
  );
};

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

  // Redux
  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const dispatch = useDispatch();

  // State
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(DEFAULT_PER_PAGE);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(DEFAULT_PAGE);
  const [tableData, setTableData] = useState([]);

  // Memoized values
  const currentRole = useMemo(() => getRoleFromUrl(), []);
  const roleKey = useMemo(
    () => (checkPathStartsWith("slaughter") ? selectedSubUser?.key || "" : ""),
    [selectedSubUser?.key]
  );

  // Fetch API data
  const fetchApiData = useCallback(
    async (pageNumber = page) => {
      dispatch(LOADING_START());
      try {
        const url = buildApiUrl({
          textValue,
          role: currentRole,
          date1: selectedDate1,
          date2: selectedDate2,
          page: pageNumber || DEFAULT_PAGE,
          perPage,
          roleKey,
        });

        const response = await axios.get(url);
        setData(response.data.results);
        setTotalRows(response.data.count);
      } catch (error) {
        console.error("Error fetching data:", error);
      } finally {
        dispatch(LOADING_END());
      }
    },
    [
      textValue,
      currentRole,
      selectedDate1,
      selectedDate2,
      perPage,
      roleKey,
      page,
      dispatch,
    ]
  );

  // Update table callback
  const updateTable = useCallback(() => {
    fetchApiData(DEFAULT_PAGE);
    setPage(DEFAULT_PAGE);
  }, [fetchApiData]);

  // Handlers
  const handlePageChange = (newPage) => {
    fetchApiData(newPage);
    setPage(newPage);
  };

  const handlePerRowsChange = (newPerRows) => {
    setPerPage(newPerRows);
    setPage(DEFAULT_PAGE);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    await fetchApiData(DEFAULT_PAGE);
    setPage(DEFAULT_PAGE);
  };

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

  const handleDateChange1 = (date) => {
    if (date) {
      setSelectedDate1(moment(date).format("YYYY-MM-DD"));
    }
  };

  const handleDateChange2 = (date) => {
    if (date) {
      setSelectedDate2(moment(date).format("YYYY-MM-DD"));
    }
  };

  const handleExcelDownload = useCallback(() => {
    openNotif({
      vertical: "top",
      horizontal: "center",
      msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
      severity: "success",
    });

    const excelUrl = buildExcelUrl({
      baseURL: axios.defaults.baseURL,
      role: currentRole,
      roleKey,
      userKey,
      textValue,
      date1: selectedDate1,
      date2: selectedDate2,
    });

    window.location.href = excelUrl;
  }, [
    openNotif,
    currentRole,
    roleKey,
    userKey,
    textValue,
    selectedDate1,
    selectedDate2,
  ]);

  // Initial data fetch and refetch when filters change
  useEffect(() => {
    fetchApiData(DEFAULT_PAGE);
    setPage(DEFAULT_PAGE);
  }, [selectedDate1, selectedDate2, perPage, roleKey, selectedSubUser?.key]);

  // Transform data to table format
  useEffect(() => {
    const transformedData = data?.map((item, i) => {
      const rowNumber =
        page === DEFAULT_PAGE ? i + 1 : i + perPage * (page - 1) + 1;

      return [
        rowNumber,
        <ShowImage
          key={`empty-${i}`}
          src={item?.assignmentInfo?.imageWithoutBar}
        />,
        <ShowImage
          key={`full-${i}`}
          src={item?.assignmentInfo?.imageWithBar}
        />,
        item?.barCode || "-",
        <VetFarmEditTrafficCode
          key={`traffic-${i}`}
          updateTable={fetchApiData}
          killHouseRequestKey={item.key}
          trafficCode={item?.trafficCode}
          isEditable={isTrafficCodeEditable(currentRole, item)}
        />,
        formatCurrency(item?.amount),
        formatDate(item?.poultryRequest?.sendDate),
        formatUserInfo(
          item.killhouseUser?.name,
          item.killhouseUser?.killHouseOperator?.user?.mobile
        ),
        item?.killer
          ? formatUserInfo(
              item.killer?.name,
              item.killer?.killHouseOperator?.user?.mobile
            )
          : "-",
        formatUserInfo(
          item.poultryRequest?.poultry?.unitName,
          item.poultryRequest?.poultry?.user?.mobile
        ),
        item?.poultryRequest?.age || "-",
        formatNumber(item.quantity),
        formatNumber(item?.weightInfo?.weight),
        formatCurrency(item?.poultryRequest?.amount),
        formatCurrency(item?.weightInfo?.killHousePrice),
        `${item.addCar?.driver?.typeCar || ""} ${
          item.addCar?.driver?.pelak || ""
        }`.trim() || "-",
        formatUserInfo(
          item.addCar?.driver?.driverName,
          item.addCar?.driver?.driverMobile
        ),
        formatNumber(item.vetAcceptedRealQuantity),
        formatNumber(item.vetAcceptedRealWeight),
        item?.poultryRequest?.orderCode || "-",
        getKillType(item),
        getSaleType(item),
        getNonReceiptState(item),
        item?.nonReceiptMessage || "-",
        formatJustDate(item?.nonReceiptCheckDate) || "-",
        formatCheckerInfo(
          item?.nonReceiptChecker,
          item?.nonReceiptCheckerMobile
        ),
        item?.message || "-",
        <SlaughterNoneRecieptOperation
          key={`operation-${i}`}
          item={item}
          updateTable={updateTable}
        />,
      ];
    });

    setTableData(transformedData || []);
  }, [data, page, perPage, currentRole, fetchApiData, updateTable]);

  // Table columns
  const tableColumns = [
    "ردیف",
    "بارنامه خالی",
    "بارنامه پر",
    "کدبار",
    "کد بهداشتی حمل و نقل",
    "قیمت مرغ زنده‌ی بار",
    "تاریخ کشتار",
    "خریدار",
    "کشتارکن اختصاصی",
    "مرغدار",
    "سن مرغ",
    "تعداد اولیه",
    "وزن اولیه بار (کیلوگرم)",
    "قیمت مرغدار",
    "قیمت کشتارگاه",
    "ماشین",
    "راننده",
    "تحویلی دامپزشک (قطعه)",
    "وزن تحویلی دامپزشک (کیلوگرم)",
    "کدسفارش کشتار",
    "نوع کشتار",
    "نوع فروش",
    "وضعیت عدم وصول",
    "توضیحات کشتارگاه",
    "تاریخ (تایید / رد)",
    "بررسی کننده",
    "توضیحات بررسی کننده",
    "عملیات",
  ];

  return (
    <Grid container justifyContent="center">
      <Grid
        container
        alignItems="start"
        justifyContent="space-between"
        gap={2}
        paddingTop={2}
        mb={1}
      >
        <Grid container alignItems="center" gap={SPACING.SMALL}>
          <Grid>
            <DatePicker
              label="از تاریخ"
              renderInput={(params) => (
                <TextField
                  {...params}
                  style={{ width: "160px" }}
                  size="small"
                />
              )}
              value={selectedDate1}
              onChange={handleDateChange1}
            />
          </Grid>
          <Grid>
            <DatePicker
              label="تا تاریخ"
              renderInput={(params) => (
                <TextField
                  {...params}
                  style={{ width: "160px" }}
                  size="small"
                />
              )}
              value={selectedDate2}
              onChange={handleDateChange2}
            />
          </Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
              value={textValue}
            />
            <Button type="submit" endIcon={<RiSearchLine />}>
              جستجو
            </Button>
          </form>
          <Tooltip title="خروجی اکسل">
            <Button color="success" onClick={handleExcelDownload}>
              <RiFileExcel2Fill size={32} />
            </Button>
          </Tooltip>
        </Grid>
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={tableColumns}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="عدم وصول"
      />
    </Grid>
  );
};
