"use client";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import LoadingSpinner from "@/src/components/reusables/ui/LoadingSpinner";
import {
  setConfirmPassword,
  setEmail,
  setPassword,
} from "@/src/redux/authSlice";
import { useAppDispatch, useAppSelector } from "@/src/redux/hook";
import axios from "axios";

import { toast } from "react-toastify";
import Image from "next/image";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import React, { useEffect, useState } from "react";
import { setIsLogin, setJoinState } from "@/src/redux/appActions";

const ResetPassword = () => {
  const [isLoading, setIsLoading] = useState(false);

  const email = useAppSelector((state) => state.auth.email);
  const password = useAppSelector((state) => state.auth.password);
  const confirmPassword = useAppSelector((state) => state.auth.confirmPassword);

  const router = useRouter();
  const dispatch = useAppDispatch();
  const searchParams = useSearchParams();

  const token = searchParams.get("token");
  const emailFromUrl = searchParams.get("email");

  useEffect(() => {
    if (emailFromUrl) {
      dispatch(setEmail(emailFromUrl));
    }
  }, [emailFromUrl, dispatch]);

  const handlePasswordReset = async () => {
    try {
      setIsLoading(true);
      const apiUrl = process.env["NEXT_PUBLIC_DEV_URL"];

      const response: any = await axios.post(
        `${apiUrl}/superadmin/reset-password`,
        {
          reset_token: token,
          email: emailFromUrl,
          password: password,
          password_confirmation: confirmPassword,
        }
      );

      if (response.data?.status === "success") {
        toast.success(response.data?.message || "Password reset successfully!");
        router.push("/admin/login");
        dispatch(setJoinState(true));
        dispatch(setIsLogin());
      } else {
        toast.error(
          response.data?.errors?.password?.[0] ||
            response.data?.message ||
            "Failed to reset password."
        );
      }
    } catch (error: any) {
      console.error("Reset password error:", error);
      toast.error(
        error.response?.data?.message ||
          "An error occurred while resetting your password. Please try again."
      );
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-100 px-4 relative">
      {/* Logo top-left */}
      <div className="absolute top-4 left-4">
        <Link
          href={"/"}
          className="px-4 sm:px-12 h-full flex items-center gap-2 shadow shadow-[#00000040]"
        >
          <div className="relative w-8 h-8 sm:w-10 sm:h-10">
            <Image
              src="/logo.svg"
              fill
              style={{ objectFit: "contain" }}
              alt="logo"
            />
          </div>
          <div className="text-base sm:text-[20px] whitespace-nowrap font-jaini">
            Happy Homes
          </div>
        </Link>
      </div>

      {/* Centered form */}
      <div className="flex justify-center items-center min-h-screen">
        <div className="bg-white rounded-lg p-6 w-full max-w-md shadow-lg text-black">
          <h2 className="text-2xl font-semibold mb-4 text-center">
            Reset Your Password
          </h2>

          <div className="my-3 flex flex-col gap-y-1">
            <label htmlFor="mail" className="text-sm font-medium" hidden>
              Email Address
            </label>
            <Input
              id="mail"
              className="border border-[#D9D9D9] p-2 !text-[12px] font-[600]"
              placeholder="Enter your email"
              value={email}
              readOnly
            />
          </div>

          <div className="my-3 flex flex-col gap-y-1">
            <label htmlFor="password" className="text-sm" hidden>
              Password
            </label>
            <Input
              name="password"
              type="password"
              className="border border-[#D9D9D9] p-2 !text-[12px] font-[600]"
              placeholder="Create a password"
              id="password"
              value={password}
              onChange={(e) => dispatch(setPassword(e.target.value))}
            />
          </div>

          <div className="my-3 flex flex-col gap-y-1">
            <label
              htmlFor="confirm_password"
              className="text-sm font-medium"
              hidden
            >
              Confirm Password
            </label>
            <Input
              type="password"
              className="border border-[#D9D9D9] p-2 !text-[12px] font-[600]"
              placeholder="Confirm your password"
              id="confirm_password"
              value={confirmPassword}
              onChange={(e) => dispatch(setConfirmPassword(e.target.value))}
            />
          </div>

          <Button
            className="bg-[#16166C] hover:bg-[#16166C]/85 cursor-pointer p-[10px] w-full"
            onClick={handlePasswordReset}
            disabled={isLoading}
          >
            {isLoading ? (
              <div className="flex items-center gap-2 justify-center">
                <LoadingSpinner />
              </div>
            ) : (
              "Submit"
            )}
          </Button>
        </div>
      </div>
    </div>
  );
};

export default ResetPassword;
