import { useContext, useEffect, useState, useMemo, useCallback } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { slaughterGetPermissionToVetService } from "../../services/slaughter-get-premisson-to-vet";
import { Box, Switch, TextField, Typography, Button } from "@mui/material";
import moment from "moment";
import { slaughterPermissionToVetService } from "../../services/slaughter-premisson-to-vet";
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 { VetFarmEditTrafficCode } from "../../../vet-farm/components/vet-farm-edit-traffic-code/VetFarmEditTrafficCode";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { slaughterEnterLoadInformationGetDashboard } from "../../services/slaughter-enter-load-information-get-dashboard";
import { Grid } from "../../../../components/grid/Grid";
import { RiSearchLine } from "react-icons/ri";
import { SlaughterEnterInformationOperation } from "../slaughter-enter-information-operation/SlaughterEnterInformationOperation";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

// Constants
const ROLES = {
  KILL_HOUSE: "KillHouse",
  PROVINCE_OPERATOR: "ProvinceOperator",
  SUPER_ADMIN: "SuperAdmin",
  VET_SUPERVISOR: "VetSupervisor",
  VET_FARM: "VetFarm",
  CITY_VET: "CityVet"
};

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 buildApiUrl = (params) => {
  const { textValue, role, date1, date2, page, perPage, roleKey } = params;
  const baseUrl = "kill_house_request_complete_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
  });

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

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

const isTrafficCodeEditable = (role, item) => {
  const adminRoles = [
    ROLES.PROVINCE_OPERATOR,
    ROLES.SUPER_ADMIN,
    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 EnterLoadInformation = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  // State
  const [checked, setChecked] = 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([]);

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

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

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

  // Fetch permission for KillHouse role
  useEffect(() => {
    if (isKillHouse) {
      dispatch(
        slaughterGetPermissionToVetService({
          role_key: roleKey
        })
      ).then((r) => {
        setChecked(r.payload.data?.[0]?.allow || false);
      });
    }
  }, [isKillHouse, selectedSubUser?.key, dispatch]);

  // 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,
          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
    ]
  );

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

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

  // Transform data to table format
  useEffect(() => {
    const transformedData = data?.map((item, i) => [
      <SlaughterEnterInformationOperation
        key={i}
        item={item}
        updateTable={updateTable}
      />,
      <Typography
        key={i}
        style={{ fontSize: "13px", color: item?.trash ? "red" : "black" }}
      >
        {item.barCode}
      </Typography>,
      <VetFarmEditTrafficCode
        key={item.key}
        updateTable={fetchApiData}
        killHouseRequestKey={item.key}
        trafficCode={item?.trafficCode}
        isEditable={isTrafficCodeEditable(currentRole, item)}
      />,
      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),
      `${item.addCar?.driver?.typeCar || ""} ${
        item.addCar?.driver?.pelak || ""
      }`.trim() || "-",
      formatUserInfo(
        item.addCar?.driver?.driverName,
        item.addCar?.driver?.driverMobile
      ),
      formatCurrency(item?.poultryRequest?.amount),
      formatCurrency(item?.weightInfo?.killHousePrice),
      formatNumber(item.vetAcceptedRealQuantity),
      formatNumber(item.vetAcceptedRealWeight),
      item?.poultryRequest?.orderCode || "-",
      item?.barDocumentStatus?.title || "-",
      item?.finalBarState || "-",
      item?.poultryRequest?.freezing ? "انجماد" : "عادی",
      item?.poultryRequest?.freeSaleInProvince
        ? "فروش آزاد"
        : "فروش دولتی" || "-"
    ]);

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

  // Initial data fetch
  useEffect(() => {
    fetchApiData(DEFAULT_PAGE);
    fetchDashboardData();
  }, []);

  // Refetch when filters change
  useEffect(() => {
    fetchApiData(DEFAULT_PAGE);
    fetchDashboardData();
    setPage(DEFAULT_PAGE);
  }, [selectedDate1, selectedDate2, perPage, selectedSubUser?.keys]);

  // 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 handleSwitchChange = () => {
    const newValue = !checked;
    dispatch(
      slaughterPermissionToVetService({
        allow: newValue
      })
    );
    setChecked(newValue);
  };

  // Table columns
  const dashboardColumns = [
    "تعداد بار",
    "مجموع تعداد اولیه",
    "مجموع وزن اولیه (کیلوگرم)",
    "مجموع تعداد تحویلی دامپزشک",
    "مجموع وزن تحویلی دامپزشک (کیلوگرم)"
  ];

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

  const dashboardRow = [
    formatNumber(dashboardData?.lenKillHouseRequest),
    formatNumber(dashboardData?.firstQuantity),
    formatNumber(dashboardData?.firstWeight),
    formatNumber(dashboardData?.vetAcceptedRealQuantity),
    formatNumber(dashboardData?.vetAcceptedRealWeight)
  ];

  return (
    <Box width="100%">
      {isKillHouse && (
        <Grid container alignItems="end" justifyContent="center">
          <Grid container alignItems="center" xs={12} justifyContent="end">
            <Grid>
              <Typography color="gray">
                دسترسی دامپزشک برای وارد کردن اطلاعات بار
              </Typography>
            </Grid>
            <Grid>
              <Switch
                checked={checked}
                onChange={handleSwitchChange}
                name="switch-state"
                inputProps={{ "aria-label": "switch with state" }}
              />
            </Grid>
          </Grid>
        </Grid>
      )}

      <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>
      </Grid>

      <Grid
        container
        justifyContent="center"
        gap={SPACING.SMALL}
        xs={12}
        mt={2}
      >
        <Grid container mt={2} mb={4} isDashboard xs={12}>
          <ResponsiveTable
            noPagination
            columns={dashboardColumns}
            data={[dashboardRow]}
            title="خلاصه اطلاعات"
            isDashboard
          />
        </Grid>

        <ResponsiveTable
          data={tableData}
          columns={tableColumns}
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
          title="درخواست های در انتظار وارد کردن اطلاعات بار"
        />
      </Grid>
    </Box>
  );
};
