import React, {
  useContext,
  useEffect,
  useState,
  useCallback,
  useRef,
} from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import { useDispatch, useSelector } from "react-redux";
import { Button, TextField, Typography, Box } from "@mui/material";
import PersonIcon from "@mui/icons-material/Person";
import PublicIcon from "@mui/icons-material/Public";
import BadgeIcon from "@mui/icons-material/Badge";
import CalendarTodayIcon from "@mui/icons-material/CalendarToday";
import AccountBoxIcon from "@mui/icons-material/AccountBox";
import BusinessIcon from "@mui/icons-material/Business";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";
import { slaughterGetDispenserUserInfoService } from "../../services/slaughter-get-dispenser-user-info";
import { provinceGetCitiesService } from "../../../province/services/province-get-cities";
import {
  slaughterHouseSubmitDispenserService,
  slaughterHouseEditDispenserService,
} from "../../services/slaughter-house-submit-dispenser-service";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

const InfoBox = ({ icon: Icon, label, value, iconSx }) => (
  <Box
    display="flex"
    alignItems={iconSx ? "flex-start" : "center"}
    gap={1}
    px={1.5}
    py={0.5}
    bgcolor="#f5f5f5"
    borderRadius={1}
  >
    <Icon color="action" sx={iconSx} />
    <Box>
      <Typography variant="caption" color="text.secondary">
        {label}
      </Typography>
      <Typography variant="body1">{value || "-"}</Typography>
    </Box>
  </Box>
);

const getValidationSchema = () =>
  yup.object({
    mobile: yup
      .string()
      .required("شماره همراه الزامی است")
      .matches(/^09\d{9}$/, "شماره تلفن باید با 09 شروع شود و 11 رقم باشد"),
  });

const DispenserForm = ({ formik, userInfo }) => {
  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container gap={SPACING.SMALL} p={2}>
        <Grid item xs={12}>
          <Typography
            variant="h6"
            style={{
              fontSize: "16px",
            }}
            gutterBottom
          >
            اطلاعات توزیع کننده
          </Typography>
        </Grid>

        {/* Additional User Info Section */}
        {userInfo && (
          <Grid container spacing={2} xs={12} mb={2}>
            <Grid item xs={12}>
              <Typography
                variant="subtitle2"
                color="text.secondary"
                gutterBottom
                sx={{ mb: 1 }}
              >
                اطلاعات شخصی
              </Typography>
            </Grid>
            <Grid item xs={12} md={4}>
              <InfoBox
                icon={BadgeIcon}
                label="کد ملی"
                value={userInfo.nationalCode || formik.values.national_id}
              />
            </Grid>
            {userInfo.fatherName && (
              <Grid item xs={12} md={4}>
                <InfoBox
                  icon={PersonIcon}
                  label="نام پدر"
                  value={userInfo.fatherName}
                />
              </Grid>
            )}
            {userInfo.birthDate && (
              <Grid item xs={12} md={4}>
                <InfoBox
                  icon={CalendarTodayIcon}
                  label="تاریخ تولد"
                  value={userInfo.birthDate}
                />
              </Grid>
            )}
            {userInfo.gender !== undefined && (
              <Grid item xs={12} md={4}>
                <InfoBox
                  icon={AccountBoxIcon}
                  label="جنسیت"
                  value={userInfo.gender ? "مرد" : "زن"}
                />
              </Grid>
            )}
            {userInfo.identityNo && userInfo.identityNo !== "0" && (
              <Grid item xs={12} md={4}>
                <InfoBox
                  icon={BadgeIcon}
                  label="شماره شناسنامه"
                  value={userInfo.identityNo}
                />
              </Grid>
            )}
            {userInfo.identitySeries && (
              <Grid item xs={12} md={4}>
                <InfoBox
                  icon={BadgeIcon}
                  label="سری شناسنامه"
                  value={userInfo.identitySeries}
                />
              </Grid>
            )}
            {userInfo.identitySerial && (
              <Grid item xs={12} md={4}>
                <InfoBox
                  icon={BadgeIcon}
                  label="سریال شناسنامه"
                  value={userInfo.identitySerial}
                />
              </Grid>
            )}
          </Grid>
        )}

        <Grid container spacing={2} xs={12}>
          <Grid item xs={12} md={6}>
            <Grid container direction="column" gap={SPACING.SMALL}>
              <Grid item xs={12}>
                <InfoBox
                  icon={PersonIcon}
                  label="نام"
                  value={formik.values.first_name}
                />
              </Grid>

              <Grid item xs={12}>
                <InfoBox
                  icon={PersonIcon}
                  label="نام خانوادگی"
                  value={formik.values.last_name}
                />
              </Grid>

              <Grid item xs={12}>
                <TextField
                  label="شماره همراه"
                  variant="outlined"
                  fullWidth
                  id="mobile"
                  name="mobile"
                  value={formik.values.mobile}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  error={Boolean(formik.errors.mobile)}
                  helperText={formik.errors.mobile}
                  inputProps={{ maxLength: 11 }}
                />
              </Grid>
            </Grid>
          </Grid>

          <Grid item xs={12} md={6}>
            <Grid container direction="column" gap={SPACING.SMALL}>
              <Grid item xs={12}>
                <InfoBox
                  icon={PublicIcon}
                  label="شهر"
                  value={formik.values.city}
                />
              </Grid>

              <Grid item xs={12}>
                <InfoBox
                  icon={BusinessIcon}
                  label="نوع توزیع کننده"
                  value={
                    formik.values.dispenser_type === "inductor"
                      ? "واسطه"
                      : formik.values.dispenser_type === "salesman"
                      ? "فروشنده"
                      : formik.values.dispenser_type === "driver"
                      ? "راننده"
                      : formik.values.dispenser_type
                  }
                />
              </Grid>

              {formik.values.dispenser_type === "driver" && (
                <>
                  <Grid item xs={12}>
                    <InfoBox
                      icon={BusinessIcon}
                      label="نوع خودرو"
                      value={formik.values.driver_car_type}
                    />
                  </Grid>
                  {formik.values.pelak && (
                    <Grid item xs={12}>
                      <InfoBox
                        icon={BadgeIcon}
                        label="پلاک خودرو"
                        value={formik.values.pelak}
                      />
                    </Grid>
                  )}
                </>
              )}

              <Grid item xs={12}>
                <InfoBox
                  icon={BusinessIcon}
                  label="سقف محدودیت"
                  value={formik.values.limitation_amount || 0}
                />
              </Grid>
            </Grid>
          </Grid>
        </Grid>

        <Grid item xs={12} mt={2}>
          <Button
            type="submit"
            variant="contained"
            color="primary"
            fullWidth
            disabled={!formik.isValid}
          >
            ثبت
          </Button>
        </Grid>
      </Grid>
    </form>
  );
};

const InquiryForm = ({ onInquiry, nationalCode, setNationalCode }) => {
  return (
    <Grid container gap={SPACING.SMALL} p={2}>
      <Grid item xs={12}>
        <TextField
          label="کد ملی"
          variant="outlined"
          fullWidth
          value={nationalCode}
          onChange={(e) => setNationalCode(e.target.value)}
          placeholder="کد ملی 10 رقمی را وارد کنید"
          inputProps={{ maxLength: 10 }}
        />
      </Grid>
      <Grid item xs={12}>
        <Button
          color="primary"
          fullWidth
          variant="contained"
          onClick={onInquiry}
          disabled={!nationalCode || nationalCode.length !== 10}
        >
          استعلام
        </Button>
      </Grid>
    </Grid>
  );
};

export const SlaughterManageDispensersForm = ({
  onClose,
  updateTable,
  dispenser,
  initialUserData,
  initialUserInfo,
  initialNationalCode,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [nationalCode, setNationalCode] = useState(
    initialNationalCode ||
      dispenser?.user?.nationalId ||
      dispenser?.national_id ||
      ""
  );
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const [userData, setUserData] = useState(
    initialUserData ||
      (dispenser
        ? {
            national_id: dispenser?.user?.nationalId || "",
            first_name: dispenser?.user?.firstName || "",
            last_name: dispenser?.user?.lastName || "",
            city: dispenser?.user?.city?.cityName || "",
            mobile: dispenser?.user?.mobile || "",
            dispenser_type: dispenser?.dispenserType || "inductor",
            limitation_amount: dispenser?.limitation_amount || 0,
            driver_car_type: dispenser?.car || "",
            pelak: dispenser?.pelak || "",
          }
        : null)
  );
  const [userFound, setUserFound] = useState(dispenser ? true : false); // eslint-disable-line no-unused-vars
  const [cities, setCities] = useState([]);
  const [userInfo, setUserInfo] = useState(initialUserInfo || null);
  const sizeUpdatedRef = useRef(!!initialUserData);

  useEffect(() => {
    dispatch(provinceGetCitiesService()).then((r) => {
      setCities(r.payload.data || []);
    });
  }, [dispatch]);

  useEffect(() => {
    if (userData && !sizeUpdatedRef.current && !dispenser) {
      sizeUpdatedRef.current = true;
      const isDesktop = window.innerWidth > 600;
      const preservedUserData = userData;
      const preservedUserInfo = userInfo;
      const preservedNationalCode = nationalCode;

      dispatch(
        OPEN_MODAL({
          title: "ثبت توزیع کننده جدید",
          content: (
            <SlaughterManageDispensersForm
              onClose={onClose}
              updateTable={updateTable}
              initialUserData={preservedUserData}
              initialUserInfo={preservedUserInfo}
              initialNationalCode={preservedNationalCode}
            />
          ),
          size: isDesktop ? 600 : 300,
        })
      );
    }
  }, [
    userData,
    dispatch,
    onClose,
    updateTable,
    dispenser,
    userInfo,
    nationalCode,
  ]);

  const handleInquiry = useCallback(() => {
    if (!nationalCode || nationalCode.length !== 10) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "لطفا کد ملی 10 رقمی معتبر وارد کنید",
        severity: "error",
      });
      return;
    }

    dispatch(
      slaughterGetDispenserUserInfoService({
        national_code: nationalCode,
        role_key:
          checkPathStartsWith("slaughter") || checkPathStartsWith("steward")
            ? selectedSubUser?.key || ""
            : "",
      })
    ).then((r) => {
      if (r.payload.error) {
        setUserFound(false);
        setUserInfo(null);
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else if (r.payload.data) {
        const response = r.payload.data;

        if (response.status === true && response.data) {
          const userDataFromApi = response.data;

          setUserFound(true);
          setUserInfo(userDataFromApi);

          setUserData({
            national_id: userDataFromApi.nationalCode || nationalCode,
            first_name: userDataFromApi.firstName || "",
            last_name: userDataFromApi.lastName || "",
            city: userDataFromApi.city || "",
            mobile: "", // Mobile is not in API response, user must enter it
            dispenser_type: "inductor",
            limitation_amount: 0,
          });

          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "اطلاعات با موفقیت دریافت شد",
            severity: "success",
          });
        } else if (response.status === false) {
          setUserFound(false);
          setUserInfo(null);
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: response.errorDescription || "خطا در دریافت اطلاعات",
            severity: "error",
          });
        } else {
          const userDataFromApi = response.data || response;

          if (userDataFromApi && userDataFromApi.nationalCode) {
            setUserFound(true);
            setUserInfo(userDataFromApi);

            setUserData({
              national_id: userDataFromApi.nationalCode || nationalCode,
              first_name: userDataFromApi.firstName || "",
              last_name: userDataFromApi.lastName || "",
              city: userDataFromApi.city || "",
              mobile: "",
              dispenser_type: "inductor",
              limitation_amount: 0,
            });

            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "اطلاعات با موفقیت دریافت شد",
              severity: "success",
            });
          } else {
            setUserFound(false);
            setUserInfo(null);
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "خطا در دریافت اطلاعات",
              severity: "error",
            });
          }
        }
      }
    });
  }, [dispatch, nationalCode, openNotif, selectedSubUser]);

  const formik = useFormik({
    initialValues: {
      national_id:
        userData?.national_id ||
        userData?.nationalCode ||
        userData?.nationalId ||
        "",
      first_name: userData?.first_name || "",
      last_name: userData?.last_name || "",
      city: userData?.city || "",
      mobile: userData?.mobile || "",
      dispenser_type: userData?.dispenser_type || "inductor",
      limitation_amount: userData?.limitation_amount || 0,
      driver_car_type: userData?.driverCarType || userData?.car || "",
      pelak: userData?.pelak || "",
    },
    validationSchema: getValidationSchema(),
    enableReinitialize: true,
    onSubmit: (values) => {
      const currentUserInfo = userInfo;
      const submitData = {
        nationalCode: values.national_id || "",
        firstName: values.first_name || "",
        lastName: values.last_name || "",
        fatherName: currentUserInfo?.fatherName || null,
        gender:
          currentUserInfo?.gender !== undefined ? currentUserInfo.gender : null,
        isLive:
          currentUserInfo?.isLive !== undefined ? currentUserInfo.isLive : true,
        identityNo: currentUserInfo?.identityNo || null,
        birthDate: currentUserInfo?.birthDate || null,
        city: values.city || currentUserInfo?.city || "",
        mobile: values.mobile,
        role: getRoleFromUrl(),
        role_key: selectedSubUser?.key || "",
      };

      if (dispenser?.key) {
        // Edit mode
        dispatch(
          slaughterHouseEditDispenserService({
            type: "update-profile",
            dispenser_key: dispenser.key,
            ...submitData,
          })
        ).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
            if (updateTable) {
              updateTable();
            }
            dispatch(CLOSE_MODAL());
          }
        });
      } else {
        // Create mode
        dispatch(slaughterHouseSubmitDispenserService(submitData)).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
            if (updateTable) {
              updateTable();
            }
            dispatch(CLOSE_MODAL());
          }
        });
      }
    },
  });

  if (!userData && !dispenser) {
    return (
      <InquiryForm
        onInquiry={handleInquiry}
        nationalCode={nationalCode}
        setNationalCode={setNationalCode}
      />
    );
  }

  return <DispenserForm formik={formik} cities={cities} userInfo={userInfo} />;
};
