"use client";
import {
  FormButton,
  FormCheckBox,
} from "@/app/components/form/forms";
import InputPassword from "@/app/components/form/inputpassword";
import { use, useEffect, useState } from "react";
import { postApiClient } from "@/utils/apiClient";
import { toast } from "react-toastify";
import Cookies from "js-cookie";
export default function UserProfile() {
  const [password, setPassword] = useState("");
  const [oldPassword, setOldPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [deleteConsent, setDeleteConsent] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [userId, setUserId] = useState("");

  const handlePasswordChange = async (e: React.FormEvent) => {
    e.preventDefault();

    // Validation
    if (!oldPassword || !newPassword || !confirmPassword) {
      toast.error("All fields are required");
      return;
    }

    if (newPassword !== confirmPassword) {
      toast.error("New password and confirm password do not match");
      return;
    }

    if (newPassword.length < 6) {
      toast.error("New password must be at least 6 characters long");
      return;
    }

    setIsLoading(true);

    try {
      const payload = {
        old_password: oldPassword,
        new_password: newPassword,
        confirmed: confirmPassword,
        u_id: userId, // Include userId in the payload
      };

      const response = await postApiClient("password-channge", payload);
      
      if (response.status !== 200) {
        throw new Error(response.message || "Failed to change password");
      }
      return response.data;
      
      toast.success("Password changed successfully!");
      setOldPassword("");
      setNewPassword("");
      setConfirmPassword("");
    } catch (error: any) {
      toast.error(error.message || "Failed to change password");
    } finally {
      setIsLoading(false);
    }
  };
  useEffect(() => {
    const userData = Cookies.get("getUser");
   
    if (userData) {
      const user = JSON.parse(userData);
    
      setUserId(user.id);
    }
  }, []);



  return (
    <div className="flex w-full flex-1 flex-col gap-4">
      <div className="flex w-full flex-col">
        <div className="flex flex-col">
          <h1 className="med">Account Settings</h1>
        </div>
        <div className="mt-5 flex w-full flex-col justify-between gap-5 align-top md:flex-row">
          <div>
            {/* Settings forms */}
            <div className="flex flex-col gap-10">
              
              {/** start code for password change */}

              <div className="grid grid-cols-1 bg-white/75 p-5 md:p-10">
                <div>
                  <h4 className="text-base/7">Change password</h4>
                  <p className="mt-1 text-sm/6">
                    Update your password associated with Morni account.
                  </p>
                </div>

                <form className="md:col-span-2" onSubmit={handlePasswordChange}>
                  <div className="grid grid-cols-2 gap-10">
                    <InputPassword
                      id="old_password"
                      name="old_password"
                      label="Old Password"
                      require={true}
                      value={oldPassword}
                      onChange={(e: any) => setOldPassword(e.target.value)}
                    />
                    <InputPassword
                      id="new_password"
                      name="new_password"
                      label="New Password"
                      require={true}
                      value={newPassword}
                      onChange={(e: any) => setNewPassword(e.target.value)}
                    />
                    <InputPassword
                      id="confirm_password"
                      name="confirm_password"
                      label="Confirm Password"
                      require={true}
                      value={confirmPassword}
                      onChange={(e: any) => setConfirmPassword(e.target.value)}
                    />
                  </div>
                   
                  

                  <div className="flex w-full md:w-[30%]">
                    <FormButton
                      id="btn_save_password"
                      label={isLoading ? "Saving..." : "Save"}
                      type="submit"
                      color="gray"
                      hairline=""
                      disabled={isLoading}
                    />
                  </div>
                </form>
              </div>
              {/** end code for password change */}
              {/** start code for logout */}

              {/* <div className="grid grid-cols-1 bg-white/75 p-5 md:p-10">
                <div>
                  <h4 className="text-base/7">Log out other sessions</h4>
                  <p className="mt-1 text-sm">
                    Please enter your password to confirm you would like to log
                    out of your other sessions across all of your devices.
                  </p>
                </div>

                <form className="md:col-span-2">
                  <div className="grid grid-cols-1 md:grid-cols-2">
                    <InputPassword
                      id="log_password"
                      name="log_password"
                      label="Password"
                      require={true}
                      value={password}
                      onChange={(e: any) => setPassword(e.target.value)}
                    />
                  </div>

                  <div className="flex w-full md:w-[30%]">
                    <FormButton
                      id="btn_logout_password"
                      label="Log Out"
                      type="submit"
                      color="gray"
                      hairline=""
                      disabled={false}
                    />
                  </div>
                </form>
              </div> */}
              {/** end code for logout */}
              {/** start code for delete account */}
              <div className="grid grid-cols-1 bg-white/75 p-5 md:p-10">
                <div>
                  <h4 className="text-base/7">Delete account</h4>
                  <p className="mt-1 text-sm">
                    No longer want to use Morni? You can delete your account
                    here. This action is not reversible. All information related
                    to this account will be deleted permanently.
                  </p>
                </div>

                <form className="grid grid-cols-1">
                  <div className="mt-5 flex w-full flex-col md:w-[50%]">
                    <FormCheckBox
                      id="check_marketing"
                      label="Sign me up to receive Morni offers, promotions and other commercial messages."
                      value={deleteConsent.toString()}
                      onChange={() => setDeleteConsent(!deleteConsent)}
                    />
                    <InputPassword
                      id="log_password"
                      name="log_password"
                      label="Password"
                      require={true}
                      value={password}
                      onChange={(e: any) => setPassword(e.target.value)}
                    />
                  </div>
                  <div className="flex w-full md:w-[30%]">
                    <FormButton
                      id="btn_delete_account"
                      label="Delete my account"
                      type="submit"
                      color="gray"
                      hairline=""
                      disabled={false}
                    />
                  </div>
                </form>
              </div>
              {/** end code for delete account */}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
