import { useContext, useEffect, useState, useMemo, useCallback } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  Box,
  TextField,
  Typography,
  Button,
  Tooltip,
  FormControlLabel,
  Checkbox,
} from "@mui/material";
import moment from "moment";
import { SPACING } from "../../../../data/spacing";
import { DatePicker } from "@mui/x-date-pickers";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useDispatch, useSelector } from "react-redux";
import { format } from "date-fns-jalali";
import axios from "axios";
import { formatTime } from "../../../../utils/formatTime";
import ShowImage from "../../../../components/show-image/ShowImage";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { VetFarmOperationOptions } from "../../../vet-farm/components/vet-farm-operations-options/VetFarmOperationOptions";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { VetFarmEditTrafficCode } from "../../../vet-farm/components/vet-farm-edit-traffic-code/VetFarmEditTrafficCode";
import { vetFarmGetFinishedBarsOverview } from "../../../vet-farm/services/vet-farm-get-bars-overview";
import { Grid } from "../../../../components/grid/Grid";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

// Constants
const ROLES = {
  KILL_HOUSE: "KillHouse",
  ADMIN_X: "AdminX",
  VET_FARM: "VetFarm",
  PROVINCE_OPERATOR: "ProvinceOperator",
  KILL_HOUSE_VET: "KillHouseVet",
  SUPER_ADMIN: "SuperAdmin",
  SUPPORTER: "Supporter",
};

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

const ITEM_STATES = {
  WAREHOUSE: "ورود به انبار",
  REGISTERED: "ثبت اطلاعات بار",
  DELETED: "حذف شده",
  ACCEPTED: "تایید تخلیه",
  PENDING: "در انتظار تخلیه",
};

const QUARANTINE_STATES = {
  CONTRADICTION: "مغایرت کد رهگیری",
  NO_CLEARANCE: "فاقد کد رهگیری",
  MERGE: "ادغام",
  NOT_APPROVED: "عدم تایید راهداری",
};

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 formatNumberFixed = (value, decimals = 2) => {
  return value ? value.toFixed(decimals).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 getItemState = (item) => {
  if (item?.wareHouseConfirmation) {
    return ITEM_STATES.WAREHOUSE;
  }
  if (item?.assignmentStateArchive !== "pending") {
    return ITEM_STATES.REGISTERED;
  }
  if (item.trash === true) {
    return ITEM_STATES.DELETED;
  }
  if (item.vetState === "accepted") {
    return ITEM_STATES.ACCEPTED;
  }
  if (item.vetState === "pending") {
    return ITEM_STATES.PENDING;
  }
  return "";
};

const getQuarantineInfo = (item) => {
  if (item?.quarantineQuantity) {
    return item.quarantineQuantity;
  }
  if (item?.quarantineCodeState) {
    const stateMap = {
      contradiction: QUARANTINE_STATES.CONTRADICTION,
      noclearance: QUARANTINE_STATES.NO_CLEARANCE,
      merge: QUARANTINE_STATES.MERGE,
    };
    return stateMap[item.quarantineCodeState] || QUARANTINE_STATES.NOT_APPROVED;
  }
  return "-";
};

const buildApiUrl = (params) => {
  const {
    textValue,
    role,
    date1,
    date2,
    page,
    perPage,
    roleKey,
    withoutBarDocument,
  } = params;
  const baseUrl = "kill_house_assignment_information/";
  const queryParams = new URLSearchParams({
    search: "filter",
    value: textValue || "",
    role: role || "",
    date1: date1 || "",
    date2: date2 || "",
    page: page || DEFAULT_PAGE,
    page_size: perPage || DEFAULT_PER_PAGE,
    without_bar_document: withoutBarDocument ? "true" : "false",
  });

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

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

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

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

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

const isTrafficCodeEditable = (role, item) => {
  if (!item?.killer?.key) {
    return false;
  }

  const editableRoles = [
    ROLES.KILL_HOUSE,
    ROLES.ADMIN_X,
    ROLES.VET_FARM,
    ROLES.PROVINCE_OPERATOR,
    ROLES.KILL_HOUSE_VET,
    ROLES.SUPER_ADMIN,
    ROLES.SUPPORTER,
  ];

  return editableRoles.includes(role);
};

const canShowDocumentCheckbox = (role) => {
  return (
    role === ROLES.SUPER_ADMIN ||
    role === ROLES.SUPPORTER ||
    role === ROLES.ADMIN_X
  );
};

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

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

  // State
  const [hasDocumentState, setHasDocumentState] = useState(false);
  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([]);
  const [dashboardData, setDashboardData] = useState([]);

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

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

  // 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,
          withoutBarDocument: hasDocumentState,
        });

        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,
      hasDocumentState,
      page,
      dispatch,
    ]
  );

  // Fetch dashboard data
  const fetchDashboardData = useCallback(() => {
    dispatch(
      vetFarmGetFinishedBarsOverview({
        selectedDate1,
        selectedDate2,
        textValue,
        hasDocumentState,
        roleKey,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  }, [
    selectedDate1,
    selectedDate2,
    textValue,
    hasDocumentState,
    roleKey,
    dispatch,
  ]);

  // 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);
    fetchDashboardData();
    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 handleChangeDocumentState = () => {
    setHasDocumentState(!hasDocumentState);
  };

  // Initial data fetch
  useEffect(() => {
    fetchApiData(DEFAULT_PAGE);
    fetchDashboardData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Refetch when filters change
  useEffect(() => {
    fetchApiData(DEFAULT_PAGE);
    fetchDashboardData();
    setPage(DEFAULT_PAGE);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedDate1, selectedDate2, hasDocumentState, perPage, roleKey]);

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

      return [
        rowNumber,
        <VetFarmOperationOptions
          key={`operation-${i}`}
          item={item}
          updateTable={fetchApiData}
          isComplete
        />,
        <Typography
          key={`state-${i}`}
          style={{ fontSize: "13px", color: textColor }}
        >
          {getItemState(item)}
        </Typography>,
        <Typography
          key={`barcode-${i}`}
          style={{ fontSize: "13px", color: textColor }}
        >
          {item.barCode}
        </Typography>,
        formatTime(item.createDate),
        getKillType(item),
        <Typography
          key={`doc-status-${i}`}
          variant="body2"
          color={item?.barDocumentStatus?.isError ? "error" : "primary"}
        >
          {item?.barDocumentStatus?.title || "-"}
        </Typography>,
        <ShowImage
          key={`image-${i}`}
          src={item?.assignmentInfo?.imageWithBar}
        />,
        formatNumber(item.acceptedRealQuantity),
        formatNumber(item?.acceptedRealWeight),
        formatNumber(item?.weightInfo?.finalIndexWeight),
        formatUserInfo(
          item.killhouseUser?.name,
          item.killhouseUser?.killHouseOperator?.user?.mobile
        ),
        item?.killer
          ? formatUserInfo(
              item.killer?.name,
              item.killer?.killHouseOperator?.user?.mobile
            )
          : "-",
        formatUserInfo(
          item.poultryRequest?.poultry?.user?.fullname,
          item.poultryRequest?.poultry?.user?.mobile
        ),
        item.poultryRequest?.poultry?.unitName || "-",
        item?.poultryRequest?.age || "-",
        formatNumber(item.quantity),
        formatNumber(item?.weightInfo?.weight),
        <Grid key={`traffic-${i}`}>
          <VetFarmEditTrafficCode
            updateTable={fetchApiData}
            killHouseRequestKey={item.key}
            trafficCode={item?.trafficCode}
            isEditable={isTrafficCodeEditable(currentRole, item)}
          />
        </Grid>,
        formatCurrency(item?.amount),
        item?.clearanceCode || "-",
        getQuarantineInfo(item),
        `${item.addCar?.driver?.typeCar || ""} ${
          item.addCar?.driver?.pelak || ""
        }`.trim() || "-",
        formatUserInfo(
          item.addCar?.driver?.driverName,
          item.addCar?.driver?.driverMobile
        ),
        item.poultryRequest?.chickenBreed || "-",
        formatNumber(item?.weightInfo?.indexWeight),
        formatCurrency(item?.poultryRequest?.amount),
        formatCurrency(item?.weightInfo?.killHousePrice),
        item?.vetFarm?.vet?.user?.fullname
          ? `${item.vetFarm.vet.user.fullname}(${item.vetFarm.vet.user.mobile})`
          : "فاقد دامپزشک",
        item.killPlace || "-",
        item.poultryRequest?.poultry?.address?.city?.name || "-",
        formatDate(item?.poultryRequest?.sendDate),
        item?.poultryRequest?.orderCode || "-",
        formatNumber(item?.wareHouseAcceptedRealQuantity),
        formatNumber(item?.wareHouseAcceptedRealWeight),
        formatNumber(item?.weightLoss),
      ];
    });

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

  // Table columns
  const dashboardColumns = [
    "تعداد بارها",
    "حجم بارها",
    "وزن بارها",
    "میانگین وزن",
    "کمترین سن ",
    "بیشترین سن ",
    "میانگین سنی",
    "بارهای دارای کد قرنطینه",
    "حجم بارهای دارای کد قرنطینه",
    "بارهای احراز شده از قرنطینه",
    "حجم بارهای احراز شده از قرنطینه",
    "بارهای فاقد کد قرنطینه",
    "حجم بارهای فاقد کد قرنطینه",
    "بارهایی که در قرنطینه و رصدیار اختلاف دارند",
    "بارهای تکمیل شده کشتارگاه",
    "حجم نهایی در کشتارگاه",
    "وزن نهایی در کشتارگاه",
    "تعداد بار ورودی به انبار",
    "حجم لاشه های انبار",
    "وزن لاشه های انبار",
    "درصد افت بار انبار",
  ];

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

  // Dashboard row data
  const renderDashboardCell = (value, isBlue = false) => (
    <Typography variant="caption" style={isBlue ? { color: "blue" } : {}}>
      {formatNumber(value)}
    </Typography>
  );

  const dashboardRow = [
    renderDashboardCell(dashboardData?.lenKillRequest, true),
    renderDashboardCell(dashboardData?.killRequestQuantity),
    renderDashboardCell(dashboardData?.killRequestWeight, true),
    <Typography key="avg-weight" variant="caption">
      {dashboardData?.avgWeight || "-"}
    </Typography>,
    renderDashboardCell(dashboardData?.minAge, true),
    renderDashboardCell(dashboardData?.maxAge),
    renderDashboardCell(dashboardData?.avgAge, true),
    renderDashboardCell(dashboardData?.lenKillRequestHasCode),
    renderDashboardCell(dashboardData?.quantityOfKillRequestHasCode, true),
    renderDashboardCell(dashboardData?.lenKillRequestHasQuarantine),
    renderDashboardCell(
      dashboardData?.quantityOfKillRequestHasQuarantine,
      true
    ),
    renderDashboardCell(dashboardData?.lenKillRequestHasNotCode),
    renderDashboardCell(dashboardData?.quantityOfKillRequestHasNotCode, true),
    renderDashboardCell(dashboardData?.differenceBar),
    renderDashboardCell(dashboardData?.lenCompleteWithKillHouse, true),
    renderDashboardCell(dashboardData?.quantityFinalKillHouse),
    renderDashboardCell(dashboardData?.weightFinalKillHouse, true),
    renderDashboardCell(dashboardData?.wareHouseBars),
    renderDashboardCell(dashboardData?.wareHouseBarsQuantity, true),
    renderDashboardCell(dashboardData?.wareHouseBarsWeight),
    <Typography key="weight-lose" variant="caption" style={{ color: "blue" }}>
      {formatNumberFixed(dashboardData?.wareHouseBarsWeightLose)}
    </Typography>,
  ];

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

  return (
    <Box width="100%" mt={2}>
      <Grid
        display="flex"
        alignItems="center"
        justifyContent="center"
        direction="row"
        gap={SPACING.SMALL}
      >
        <Grid container justifyContent="center" gap={SPACING.SMALL} xs={12}>
          <Grid container alignItems="center" gap={SPACING.SMALL} xs={12}>
            <Grid style={{ width: "150px" }}>
              <DatePicker
                label="از تاریخ"
                renderInput={(params) => <TextField {...params} />}
                value={selectedDate1}
                onChange={handleDateChange1}
              />
            </Grid>
            <Grid style={{ width: "150px" }}>
              <DatePicker
                label="تا تاریخ"
                renderInput={(params) => <TextField {...params} />}
                value={selectedDate2}
                onChange={handleDateChange2}
              />
            </Grid>
            <form onSubmit={handleSubmit}>
              <TextField
                autoComplete="off"
                size="small"
                label="جستجو"
                variant="outlined"
                style={{ width: 250 }}
                onChange={handleTextChange}
                value={textValue}
              />
              <Button type="submit" endIcon={<RiSearchLine />}>
                جستجو
              </Button>
            </form>
            {!!data?.length && (
              <Grid>
                <Tooltip title="خروجی اکسل">
                  <a href={excelUrl} rel="noreferrer">
                    <Button color="success">
                      <RiFileExcel2Fill size={32} />
                    </Button>
                  </a>
                </Tooltip>
              </Grid>
            )}
            {showDocumentCheckbox && (
              <FormControlLabel
                control={
                  <Checkbox
                    checked={hasDocumentState}
                    onChange={handleChangeDocumentState}
                    name="document-checkbox"
                  />
                }
                label="بدون وضعیت سند"
              />
            )}
          </Grid>
          <Grid container mt={2} mb={4} isDashboard xs={12}>
            <ResponsiveTable
              title="خلاصه اطلاعات"
              noPagination
              isDashboard
              columns={dashboardColumns}
              data={[dashboardRow]}
            />
          </Grid>
          <ResponsiveTable
            data={tableData}
            columns={tableColumns}
            handlePageChange={handlePageChange}
            totalRows={totalRows}
            page={page}
            perPage={perPage}
            handlePerRowsChange={handlePerRowsChange}
            title="بارهای تکمیل شده"
          />
        </Grid>
      </Grid>
    </Box>
  );
};
