import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import MkdSDK from "../utils/MkdSDK";
import { GlobalContext, showToast } from "../globalContext";
import { AuthContext, tokenExpireError } from "../authContext";
import { InteractiveButton } from "Components/InteractiveButton";
import {
  getUserDetailsByIdAPI,
  updateUserDetailsAPI,
  createOrUpdateUserProfilePhotoAPI,
} from "Src/services/userService";
import { uploadS3FilesAPI } from "Src/services/workOrderService";

import PhotoUpload from "Components/PhotoUpload";

let sdk = new MkdSDK();

const ProfilePage = () => {
  const schema = yup.object().shape({
    first_name: yup.string().required(),
    last_name: yup.string().required(),
    email: yup.string().email().required(),
    company_name: yup.string().required(),
  });

  const { dispatch } = React.useContext(AuthContext);
  const { state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const [oldEmail, setOldEmail] = useState("");
  const [submitLoading, setSubmitLoading] = useState(false);
  const [userId, setUserId] = React.useState(null);
  const [photoUrl, setPhotoUrl] = React.useState(null);
  const [companyName, setCompanyName] = React.useState(null);
  const [sub, setSub] = React.useState(null);

  const {
    register,
    handleSubmit,
    setError,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "profile",
      },
    });

    const userId = localStorage.getItem("user");
    setUserId(userId);

    if (userId) {
      (async function () {
        try {
          const result = await getUserDetailsByIdAPI(Number(userId));
          if (!result.error) {
            setValue("email", result.model.email);
            setValue("first_name", result.model.first_name);
            setValue("last_name", result.model.last_name);
            setValue("company_name", result.model.company_name);
            setOldEmail(result.model.email);
            setPhotoUrl(result.model.photo);

            setCompanyName(result.model.company_name);

            dispatch({
              type: "SET_PROFILE",
              payload: {
                photo: result.model.photo,
                companyName: result.model.company_name,
              },
            });
          } else {
            showToast(globalDispatch, result.message, 4000, "error");
            return;
          }
        } catch (error) {
          tokenExpireError(globalDispatch, error.message, 4000);
        }
      })();
    }
  }, []);

  const onSubmit = async (data) => {
    try {
      setSubmitLoading(true);
      if (oldEmail !== data.email) {
        const emailResult = await sdk.updateEmail(data.email);
        if (!emailResult.error) {
          showToast(dispatch, "Email Updated", 2000);
        } else {
          if (emailResult.validation) {
            const keys = Object.keys(emailResult.validation);
            for (let i = 0; i < keys.length; i++) {
              const field = keys[i];
              setError(field, {
                type: "manual",
                message: emailResult.validation[field],
              });
            }
          }
        }
      }

      if (data.password.length > 0) {
        const passwordResult = await sdk.updatePassword(data.password);
        if (!passwordResult.error) {
          showToast(globalDispatch, "Password Updated", 2000);
        } else {
          if (passwordResult.validation) {
            const keys = Object.keys(passwordResult.validation);
            for (let i = 0; i < keys.length; i++) {
              const field = keys[i];
              setError(field, {
                type: "manual",
                message: passwordResult.validation[field],
              });
            }
          }
        }
      }

      if (
        data.first_name.length > 0 ||
        data.last_name.length > 0 ||
        data.company_name.length > 0
      ) {
        const profileResult = await updateUserDetailsAPI({
          id: userId,
          first_name: data.first_name,
          last_name: data.last_name,
          company_name: data.company_name,
        });
        if (!profileResult.error) {
          dispatch({
            type: "SET_PROFILE",
            payload: {
              photo: photoUrl,
              companyName: data.company_name,
            },
          });
          showToast(globalDispatch, "Profile Updated", 2000);
        } else {
          showToast(globalDispatch, "Profile Update Failed", 2000, "error");
        }
      }

      setSubmitLoading(false);
    } catch (error) {
      setSubmitLoading(false);

      setError("email", {
        type: "manual",
        message: error.message,
      });
      tokenExpireError(
        dispatch,
        error.response.data.message
          ? error.response.data.message
          : error.message
      );
    }
  };

  const handlePhotoUpload = async (formData) => {
    try {
      const result = await uploadS3FilesAPI(formData);
      if (!result.error) {
        let attachmentsArr = JSON.parse(result.attachments);
        const payload = {
          id: userId,
          photo: attachmentsArr[0],
        };
        const photoResult = await createOrUpdateUserProfilePhotoAPI(payload);

        if (!photoResult.error) {
          setPhotoUrl(attachmentsArr[0]);
          showToast(globalDispatch, photoResult.message, 5000);
          dispatch({
            type: "SET_PROFILE",
            payload: {
              photo: attachmentsArr[0],
              companyName: companyName,
            },
          });
          // window.location.reload();
        } else {
          showToast(globalDispatch, photoResult.message, 3000, "error");
          return;
        }
      } else {
        showToast(globalDispatch, result.message, 2000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message, 4000);
    }
  };

  const SubscriptionType = localStorage.getItem("UserSubscription");

  React.useEffect(() => {
    const userId = localStorage.getItem("user");

    if (userId) {
      (async function () {
        try {
          const result = await getUserDetailsByIdAPI(userId);

          if (!result?.error) {
            localStorage.setItem("photo", result?.model?.photo);
            setSub(result?.model?.subscription);
            localStorage.setItem(
              "UserSubscription",
              result?.model?.subscription
            );
          }
        } catch (error) {}
      })();
    }
  }, []);

  const subscriptions = [
    { id: 1, type: "Vocal Production Subscription" },
    { id: 2, type: "Producer/Client Platform Subscription" },
    { id: 3, type: "Both (Vocal production and producer/client platform)" },
  ];

  const userSub = subscriptions.find((elem) => elem.id == sub);

  return (
    <div className="p-4 h-full max-w-screen md:p-4 lg:p-6 xl:p-8">
      <div className="grid grid-cols-5 gap-8">
        {/* Left Column - Personal Information */}
        <div className="col-span-5 xl:col-span-3">
          <div className="rounded border shadow-default border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
            <div className="px-7 py-4 border-b border-strokedark dark:border-strokedark">
              <h3 className="font-medium text-white dark:text-white">
                Personal Information
              </h3>
            </div>

            <div className="p-7">
              <form onSubmit={handleSubmit(onSubmit)}>
                <div className="flex flex-col gap-5 justify-between mb-5 sm:flex-row">
                  <div className="w-full sm:w-[45%]">
                    <label className="block mb-3 text-sm font-medium text-white dark:text-white">
                      First Name
                    </label>
                    <div className="relative">
                      <span className="left-4.5 absolute top-4">
                        <svg
                          className="fill-current"
                          width="20"
                          height="20"
                          viewBox="0 0 20 20"
                        >
                          {/* User icon SVG path */}
                        </svg>
                      </span>
                      <input
                        className="pl-11.5 pr-4.5 w-full rounded border border-form-strokedark bg-form-input py-3 text-white focus:border-primary focus-visible:outline-none dark:border-strokedark dark:bg-meta-4 dark:text-white dark:focus:border-primary"
                        type="text"
                        {...register("first_name")}
                        placeholder="First Name"
                      />
                    </div>
                    <p className="mt-1 text-sm text-danger">
                      {errors.first_name?.message}
                    </p>
                  </div>

                  <div className="w-full sm:w-[45%]">
                    <label className="block mb-3 text-sm font-medium text-white dark:text-white">
                      Last Name
                    </label>
                    <input
                      className="px-4.5 w-full rounded border border-form-strokedark bg-form-input py-3 text-white focus:border-primary focus-visible:outline-none dark:border-strokedark dark:bg-meta-4 dark:text-white dark:focus:border-primary"
                      type="text"
                      {...register("last_name")}
                      placeholder="Last Name"
                    />
                    <p className="mt-1 text-sm text-danger">
                      {errors.last_name?.message}
                    </p>
                  </div>
                </div>

                {/* Company Name */}
                <div className="mb-5">
                  <label className="block mb-3 text-sm font-medium text-white dark:text-white">
                    Company Name
                  </label>
                  <input
                    className="px-4.5 w-full rounded border border-form-strokedark bg-form-input py-3 text-white focus:border-primary focus-visible:outline-none dark:border-strokedark dark:bg-meta-4 dark:text-white dark:focus:border-primary"
                    type="text"
                    {...register("company_name")}
                    placeholder="Company Name"
                  />
                  <p className="mt-1 text-sm text-danger">
                    {errors.company_name?.message}
                  </p>
                </div>

                {/* Email */}
                <div className="mb-5">
                  <label className="block mb-3 text-sm font-medium text-white dark:text-white">
                    Email Address
                  </label>
                  <div className="relative">
                    <span className="left-4.5 absolute top-4">
                      <svg
                        className="fill-current"
                        width="20"
                        height="20"
                        viewBox="0 0 20 20"
                      >
                        {/* Email icon SVG path */}
                      </svg>
                    </span>
                    <input
                      className="pl-11.5 pr-4.5 w-full rounded border border-form-strokedark bg-form-input py-3 text-white focus:border-primary focus-visible:outline-none dark:border-strokedark dark:bg-meta-4 dark:text-white dark:focus:border-primary"
                      type="email"
                      {...register("email")}
                      readOnly={authState.role === "client"}
                      placeholder="Email Address"
                    />
                  </div>
                  <p className="mt-1 text-sm text-danger">
                    {errors.email?.message}
                  </p>
                </div>

                {/* Password */}
                <div className="mb-5">
                  <label className="block mb-3 text-sm font-medium text-white dark:text-white">
                    Password
                  </label>
                  <input
                    className="px-4.5 w-full rounded border border-form-strokedark bg-form-input py-3 text-white focus:border-primary focus-visible:outline-none dark:border-strokedark dark:bg-meta-4 dark:text-white dark:focus:border-primary"
                    type="password"
                    {...register("password")}
                    placeholder="Enter password"
                  />
                  <p className="mt-1 text-sm text-danger">
                    {errors.password?.message}
                  </p>
                </div>

                {/* Subscription (if member) */}
                {/* {authState?.role === "member" && (
                  <div className="mb-5">
                    <label className="block mb-3 text-sm font-medium text-white dark:text-white">
                      Subscription
                    </label>
                    <input
                      className="px-4.5 w-full rounded border border-form-strokedark bg-form-input py-3 text-white focus:border-primary focus-visible:outline-none dark:border-strokedark dark:bg-meta-4 dark:text-white dark:focus:border-primary"
                      type="text"
                      readOnly
                      value={userSub?.type || ""}
                    />
                  </div>
                )} */}

                {/* Buttons */}
                <div className="gap-4.5 mt-5 flex justify-end">
                  <button
                    className="flex justify-center px-6 py-2 font-medium text-white rounded border border-strokedark hover:shadow-1 dark:border-strokedark dark:text-white"
                    type="button"
                  >
                    Cancel
                  </button>
                  <InteractiveButton
                    loading={submitLoading}
                    disabled={submitLoading}
                    type="submit"
                    className="flex justify-center px-6 py-2 font-medium rounded bg-primary text-gray hover:bg-opacity-90"
                  >
                    Save
                  </InteractiveButton>
                </div>
              </form>
            </div>
          </div>
        </div>

        {/* Right Column - Photo Upload */}
        <div className="col-span-5 xl:col-span-2">
          <div className="rounded border shadow-default border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
            <div className="px-7 py-4 border-b border-strokedark dark:border-strokedark">
              <h3 className="font-medium text-white dark:text-white">
                Your Photo
              </h3>
            </div>
            <div className="p-7">
              <div className="flex gap-3 items-center mb-4">
                {photoUrl && (
                  <div className="w-14 h-14 rounded-full">
                    <img
                      src={photoUrl}
                      alt="Profile"
                      className="object-cover w-full h-full rounded-full"
                    />
                  </div>
                )}
                <div>
                  <span className="mb-1.5 text-white dark:text-white">
                    Edit your photo
                  </span>
                </div>
              </div>

              <PhotoUpload maxFileSize={2} setFileUpload={handlePhotoUpload} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ProfilePage;
