import React, { useContext, useEffect, useState } from "react";
import {
  Typography,
  Box,
  Paper,
  Divider,
  IconButton,
  Grid,
  useTheme,
  Button,
  TextField,
  Autocomplete,
} from "@mui/material";
import EditIcon from "@mui/icons-material/Edit";
import PersonIcon from "@mui/icons-material/Person";
import PhoneIcon from "@mui/icons-material/Phone";
import BadgeIcon from "@mui/icons-material/Badge";
import CakeIcon from "@mui/icons-material/Cake";
import LocationCityIcon from "@mui/icons-material/LocationCity";
import LockIcon from "@mui/icons-material/Lock";
import { useDispatch, useSelector } from "react-redux";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { formatJustDate } from "../../../../utils/formatTime";
import { getUserProfile } from "../../services/getUserProfile";
import { ChangeProfile } from "../change-profile/ChangeProfile";
import { motion } from "framer-motion";
import { ChangePasswordForm } from "../change-password-form/ChangePasswordForm";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { changeProfileFactorInfo } from "../../services/changeProfileInfo";
import { AppContext } from "../../../../contexts/AppContext";
import {
  slaughterGetCitiesService,
  slaughterGetProvinceService,
} from "../../../slaughter-house/services/slaughter-get-provinces";

const fadeInVariant = {
  hidden: { opacity: 0, y: 20 },
  visible: { opacity: 1, y: 0, transition: { duration: 0.5 } },
};

export const BasicProfileInformation = () => {
  const { userProfile } = useSelector((state) => state.userSlice);
  const dispatch = useDispatch();
  const theme = useTheme();
  const [provinceData, setProvinceData] = useState([]);
  const [cityData, setCityData] = useState([]);
  const [openNotif] = useContext(AppContext);

  const getProfile = () => {
    dispatch(getUserProfile());
  };

  useEffect(() => {
    getProfile();
  }, [dispatch]);

  const validationSchema = Yup.object({
    nationalId: Yup.string().required("شناسه ملی الزامی است"),
    registrationNumber: Yup.string().required("شماره ثبت الزامی است"),
    economicalCode: Yup.string().required("کد اقتصادی الزامی است"),
    address: Yup.string().required("نشانی الزامی است"),
    unitName: Yup.string().required("نام واحد الزامی است"),
    postalCode: Yup.string()
      .matches(/^[0-9]{10}$/, "کد پستی باید 10 رقم باشد")
      .required("کد پستی الزامی است"),
    province: Yup.string()
      .required("این فیلد اجباری است!")
      .typeError("لطفا فیلد را به درستی وارد کنید!"),
    city: Yup.string()
      .required("این فیلد اجباری است!")
      .typeError("لطفا فیلد را به درستی وارد کنید!"),
  });

  const formik = useFormik({
    initialValues: {
      nationalId: userProfile?.unitNationalId || "",
      registrationNumber: userProfile?.unitRegistrationNumber || "",
      address: userProfile?.unitAddress || "",
      postalCode: userProfile?.unitPostalCode || "",
      economicalCode: userProfile?.unitEconomicalNumber || "",
      unitName: userProfile?.unitName || "",
      province: userProfile?.unitProvince || "",
      city: userProfile?.unitCity || "",
    },
    validationSchema,
    onSubmit: (values) => {
      dispatch(LOADING_START());
      dispatch(
        changeProfileFactorInfo({
          userprofile_key: userProfile?.key,
          unit_name: values.unitName,
          unit_national_id: values.nationalId,
          unit_registration_number: values.registrationNumber,
          unit_province: values.province,
          unit_city: values.city,
          unit_postal_code: values.postalCode,
          unit_address: values.address,
          unit_economical_number: values.economicalCode,
        })
      ).then((r) => {
        if (r.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی پیش آمده است!",
            severity: "error",
          });
        } else {
          dispatch(getUserProfile());
          dispatch(LOADING_END());

          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
        dispatch(LOADING_END());
      });
    },
  });

  useEffect(() => {
    dispatch(slaughterGetProvinceService()).then((r) => {
      setProvinceData(r.payload.data);
    });
  }, []);

  useEffect(() => {
    if (formik.values.province) {
      setCityData(
        [],
        dispatch(slaughterGetCitiesService(formik.values.province)).then(
          (r) => {
            setCityData(r.payload.data);
          }
        )
      );
    }
  }, [formik.values.province]);

  useEffect(() => {
    formik.validateForm();
  }, [dispatch, userProfile]);

  const userData = [
    {
      icon: <PersonIcon color="primary" />,
      label: "نام و نام خانوادگی",
      value: userProfile?.fullname || "نامشخص",
    },
    {
      icon: <PhoneIcon color="secondary" />,
      label: "موبایل",
      value: userProfile?.mobile || "نامشخص",
    },
    {
      icon: <BadgeIcon color="error" />,
      label: "کدملی",
      value: userProfile?.nationalId || "نامشخص",
    },
    {
      icon: <BadgeIcon color="info" />,
      label: "شماره شناسنامه",
      value: userProfile?.nationalCode || "نامشخص",
    },
    {
      icon: <CakeIcon color="success" />,
      label: "تاریخ تولد",
      value: userProfile?.birthday
        ? formatJustDate(userProfile?.birthday)
        : "نامشخص",
    },
    {
      icon: <LocationCityIcon color="warning" />,
      label: "استان",
      value: userProfile?.province || "نامشخص",
    },
    {
      icon: <LocationCityIcon color="warning" />,
      label: "شهر",
      value: userProfile?.city || "نامشخص",
    },
  ];

  return (
    <Box
      display="flex"
      flexDirection="column"
      gap={1}
      sx={{ width: "100%", padding: 1 }}
    >
      <motion.div
        initial="hidden"
        animate="visible"
        variants={fadeInVariant}
        style={{ width: "100%" }}
      >
        <Paper
          elevation={4}
          sx={{
            padding: 2,
            borderRadius: 3,
            bgcolor: theme.palette.background.paper,
          }}
        >
          <Box
            display="flex"
            justifyContent="space-between"
            alignItems="center"
            mb={1}
          >
            <Box display="flex" alignItems="center" gap={1}>
              <PersonIcon color="primary" />
              <Typography variant="subtitle2" fontWeight="bold" color="primary">
                اطلاعات کاربری
              </Typography>
            </Box>
            <IconButton
              color="primary"
              size="small"
              onClick={() => {
                dispatch(
                  DRAWER({
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    content: <ChangeProfile user={userProfile} />,
                    title: "ویرایش اطلاعات کاربری",
                  })
                );
              }}
            >
              <EditIcon />
            </IconButton>
          </Box>

          <Grid container spacing={1}>
            {userData.map((item, index) => (
              <Grid item xs={12} sm={4} md={3} key={index}>
                <Box display="flex" alignItems="center" gap={1}>
                  {item.icon}
                  <Box>
                    <Typography
                      variant="body2"
                      fontWeight="500"
                      color="text.secondary"
                    >
                      {item.label}
                    </Typography>
                    <Typography
                      variant="body2"
                      fontWeight="600"
                      color="text.primary"
                    >
                      {item.value}
                    </Typography>
                  </Box>
                </Box>
              </Grid>
            ))}
          </Grid>

          <Divider sx={{ marginY: 2 }} />

          {(userProfile?.role?.includes("ProvinceOperator") ||
            userProfile?.role?.includes("KillHouse")) && (
            <>
              <Box
                display="flex"
                justifyContent="space-between"
                alignItems="center"
                mb={2}
              >
                <Box display="flex" alignItems="center" gap={1}>
                  <PersonIcon color="primary" />
                  <Typography
                    variant="subtitle2"
                    fontWeight="bold"
                    color="primary"
                  >
                    اطلاعات صدور فاکتور
                  </Typography>
                </Box>
              </Box>

              <form onSubmit={formik.handleSubmit}>
                <Grid container spacing={2} alignItems="center">
                  <Grid item xs={12} sm={4}>
                    <TextField
                      size="small"
                      fullWidth
                      label="نام واحد"
                      name="unitName"
                      value={formik.values.unitName}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      error={
                        formik.touched.unitName &&
                        Boolean(formik.errors.unitName)
                      }
                      helperText={
                        formik.touched.unitName && formik.errors.unitName
                      }
                    />
                  </Grid>
                  <Grid item xs={12} sm={4}>
                    <TextField
                      size="small"
                      fullWidth
                      label="شناسه ملی"
                      name="nationalId"
                      value={formik.values.nationalId}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      error={
                        formik.touched.nationalId &&
                        Boolean(formik.errors.nationalId)
                      }
                      helperText={
                        formik.touched.nationalId && formik.errors.nationalId
                      }
                    />
                  </Grid>
                  <Grid item xs={12} sm={4}>
                    <TextField
                      size="small"
                      fullWidth
                      label="شماره ثبت"
                      name="registrationNumber"
                      value={formik.values.registrationNumber}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      error={
                        formik.touched.registrationNumber &&
                        Boolean(formik.errors.registrationNumber)
                      }
                      helperText={
                        formik.touched.registrationNumber &&
                        formik.errors.registrationNumber
                      }
                    />
                  </Grid>

                  <Grid item xs={12} sm={4}>
                    <TextField
                      size="small"
                      fullWidth
                      label="کد اقتصادی"
                      name="economicalCode"
                      value={formik.values.economicalCode}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      error={
                        formik.touched.economicalCode &&
                        Boolean(formik.errors.economicalCode)
                      }
                      helperText={
                        formik.touched.economicalCode &&
                        formik.errors.economicalCode
                      }
                    />
                  </Grid>

                  <Grid item xs={12} sm={4}>
                    <TextField
                      size="small"
                      fullWidth
                      label="کد پستی"
                      name="postalCode"
                      value={formik.values.postalCode}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      error={
                        formik.touched.postalCode &&
                        Boolean(formik.errors.postalCode)
                      }
                      helperText={
                        formik.touched.postalCode && formik.errors.postalCode
                      }
                    />
                  </Grid>

                  <Grid item xs={12} sm={4}>
                    <TextField
                      size="small"
                      fullWidth
                      label="نشانی"
                      name="address"
                      value={formik.values.address}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      error={
                        formik.touched.address && Boolean(formik.errors.address)
                      }
                      helperText={
                        formik.touched.address && formik.errors.address
                      }
                    />
                  </Grid>

                  <Grid item xs={12} sm={4}>
                    <Autocomplete
                      size="small"
                      style={{ width: "100%" }}
                      disablePortal
                      id="province"
                      options={
                        provinceData
                          ? provinceData.map((i) => ({
                              id: i.name,
                              label: i.name,
                            }))
                          : []
                      }
                      onChange={(e, value) => {
                        formik.setFieldValue("province", value ? value.id : "");
                        formik.setFieldValue("city", "");
                      }}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label={
                            userProfile?.unitProvince
                              ? `استان ${userProfile?.unitProvince}`
                              : "استان را انتخاب کنید"
                          }
                        />
                      )}
                    />
                  </Grid>

                  <Grid item xs={12} sm={4}>
                    <Autocomplete
                      size="small"
                      minWidth={210}
                      style={{ width: "100%" }}
                      disabled={!formik.values.province}
                      disablePortal
                      id="city"
                      options={
                        cityData
                          ? cityData.map((i) => ({ id: i.name, label: i.name }))
                          : []
                      }
                      onChange={(e, value) => {
                        formik.setFieldValue("city", value ? value.id : "");
                      }}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label={
                            userProfile?.unitCity
                              ? `شهر ${userProfile?.unitCity}`
                              : "شهر را انتخاب کنید"
                          }
                        />
                      )}
                    />
                  </Grid>

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

          <Box
            display="flex"
            justifyContent="space-between"
            alignItems="center"
            mt={2}
          >
            <Box display="flex" alignItems="center" gap={1}>
              <LockIcon color="secondary" />
              <Typography
                variant="subtitle2"
                fontWeight="bold"
                color="secondary"
              >
                تغییر رمز عبور
              </Typography>
            </Box>
            <IconButton
              color="secondary"
              size="small"
              onClick={() => {
                dispatch(
                  DRAWER({
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    title: "تغییر رمز عبور",
                    content: <ChangePasswordForm />,
                  })
                );
              }}
            >
              <EditIcon />
            </IconButton>
          </Box>
        </Paper>
      </motion.div>
    </Box>
  );
};
