import { useFormik } from "formik";
import { type FC, useEffect } from "react";
import * as Yup from "yup";
import Button from "@/components/Button";
import { TickCircle } from "iconsax-react";
import Input from "@/components/Input";
import Textarea from "@/components/Textarea";
import SwitchComponent from "@/components/Switch";
import {
  useGetUserById,
  useUpdateUser,
} from "./hooks/useUserData";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "react-toastify";
import { extractErrorMessage } from "@/config/func";
import { Paths } from "@/config/Paths";
import type { CreateUserType } from "./types/Types";

const initialValues: CreateUserType = {
  phone: "",
  firstName: "",
  lastName: "",
  address: "",
  gender: true,
  maxCredit: 0,
};

const validationSchema = Yup.object({
  phone: Yup.string()
    .required("شماره موبایل اجباری است"),
  firstName: Yup.string().required("نام اجباری است"),
  lastName: Yup.string().required("نام خانوادگی اجباری است"),
  address: Yup.string(),
  maxCredit: Yup.number().min(0, "اعتبار نمی‌تواند منفی باشد"),
});

const UpdateUser: FC = () => {
  const navigate = useNavigate();
  const { id: userId } = useParams<{ id: string }>();
  const { data: userData, isLoading: isLoadingUser } = useGetUserById(
    userId ?? null,
    !!userId
  );
  const { mutate: updateUser, isPending } = useUpdateUser();

  const formik = useFormik<CreateUserType>({
    initialValues,
    validationSchema,
    onSubmit: (values) => {
      if (!userId) return;
      updateUser(
        { userId, params: values },
        {
          onSuccess: () => {
            toast.success("مشتری با موفقیت ویرایش شد");
            navigate(Paths.users.list);
          },
          onError: (error) => toast.error(extractErrorMessage(error)),
        }
      );
    },
  });

  useEffect(() => {
    if (userData?.data) {
      const u = userData.data;
      formik.setValues({
        phone: u.phone ?? "",
        firstName: u.firstName ?? "",
        lastName: u.lastName ?? "",
        address: u.addresse ?? "",
        gender: u.gender ?? true,
        maxCredit: u.maxCredit ?? 0,
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [userData?.data]);

  if (isLoadingUser) {
    return (
      <div className="mt-5">
        <div className="flex justify-center items-center h-64">
          <div className="text-lg">در حال بارگذاری...</div>
        </div>
      </div>
    );
  }

  if (!userId || (!userData?.data && !isLoadingUser)) {
    return (
      <div className="mt-5">
        <div className="flex justify-center items-center h-64">
          <div className="text-lg text-red-500">مشتری یافت نشد</div>
        </div>
      </div>
    );
  }

  return (
    <div className="mt-5">
      <div className="flex justify-between items-center">
        <h1 className="text-lg font-light">ویرایش مشتری</h1>
        <Button
          className="w-fit px-6"
          onClick={() => formik.handleSubmit()}
          isLoading={isPending}
        >
          <div className="flex gap-1.5">
            <TickCircle size={18} color="black" />
            <div className="text-[13px] font-light">ذخیره</div>
          </div>
        </Button>
      </div>

      <div className="mt-8 bg-white p-6 rounded-3xl flex-1">
        <div className="rowTwoInput">
          <Input
            label="موبایل"
            placeholder="۰۹۱۲۳۴۵۶۷۸۹"
            {...formik.getFieldProps("phone")}
            error_text={
              formik.touched.phone && formik.errors.phone
                ? formik.errors.phone
                : ""
            }
          />
          <Input
            label="نام"
            placeholder="نام"
            {...formik.getFieldProps("firstName")}
            error_text={
              formik.touched.firstName && formik.errors.firstName
                ? formik.errors.firstName
                : ""
            }
          />
        </div>

        <div className="mt-6">
          <Input
            label="نام خانوادگی"
            placeholder="نام خانوادگی"
            {...formik.getFieldProps("lastName")}
            error_text={
              formik.touched.lastName && formik.errors.lastName
                ? formik.errors.lastName
                : ""
            }
          />
        </div>

        <div className="mt-6">
          <Textarea
            label="آدرس"
            placeholder="آدرس"
            {...formik.getFieldProps("address")}
          />
        </div>

        <div className="mt-6">
          <label className="block text-xs text-description mb-1">جنسیت</label>
          <SwitchComponent
            active={formik.values.gender}
            onChange={(value) => formik.setFieldValue("gender", value)}
            label={formik.values.gender ? "مرد" : "زن"}
          />
        </div>

        <div className="mt-6">
          <Input
            label="حداکثر اعتبار (ریال)"
            type="number"
            min={0}
            placeholder="۰"
            {...formik.getFieldProps("maxCredit")}
            error_text={
              formik.touched.maxCredit && formik.errors.maxCredit
                ? formik.errors.maxCredit
                : ""
            }
          />
        </div>
      </div>
    </div>
  );
};

export default UpdateUser;
