import { Mail, Lock, Eye, EyeOff, ArrowRight } from "lucide-react";
import { motion } from "framer-motion";
import { useState } from "react";
import { useForm, Controller, Resolver } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { Form } from "antd";
import toast from "react-hot-toast";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import { useAuth } from "@/hooks/useAuth";
import type { ILoginInput } from "../types";
import { Link } from "react-router-dom";

const loginSchema = yup.object({
  email: yup.string().email("Invalid email").required("Email is required"),
  password: yup.string().required("Password is required"),
});

const forgotSchema = yup.object({
  email: yup.string().email("Invalid email").required("Email is required"),
});

export default function LoginPage() {
  const { login } = useAuth();
  const [isForgotPassword, setForgotPassword] = useState(false);
  const [showPassword, setShowPassword] = useState(false);

  const resolver = yupResolver(
    isForgotPassword ? forgotSchema : loginSchema
  ) as Resolver<ILoginInput>;

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting },
  } = useForm<ILoginInput>({
    defaultValues: { email: "", password: "" },
    resolver,
  });

  const onSubmit = async (values: ILoginInput) => {
    if (isForgotPassword) {
      try {
        const response = await API_Instance.post(API_Constants.forgotPassword, {
          email: values.email,
        });
        toast.success(
          response.data.message ||
            "Verification email sent to your registered address."
        );
        reset();
        setForgotPassword(false);
      } catch (error) {
        toast.error(getAxiosErrorMessage(error));
      }
      return;
    }

    await login(values);
    reset();
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 40 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.6 }}
      className="min-h-screen flex items-center justify-center px-4 bg-gray-50"
    >
      <motion.div
        initial={{ scale: 0.9, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        transition={{ duration: 0.5 }}
        className="w-full max-w-md bg-white rounded-2xl shadow-xl border border-gray-100"
      >
        <div className="p-8">
          {/* HEADER */}
          <Link
            to={"/landing"}
            className="w-full flex-shrink-0 flex items-center justify-center cursor-pointer gap-2 mb-4"
          >
            <img src="/logo.png" alt="logo" className="h-[5rem] w-[5rem]" />
          </Link>
          <div className="text-center mb-5">
            <h2 className="text-3xl font-extrabold text-brand-navy">
              {isForgotPassword ? "Forgot Password" : "Welcome Back"}
            </h2>
            <p className="text-gray-500">
              {isForgotPassword
                ? "Enter your email to receive the reset link."
                : "Sign in to access your dashboard"}
            </p>
          </div>
          {/* FORM */}
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
            {/* EMAIL */}
            <Form.Item
              validateStatus={errors.email ? "error" : ""}
              help={errors.email?.message}
            >
              <Controller
                name="email"
                control={control}
                render={({ field }) => (
                  <div className="flex flex-col">
                    <label className="text-sm font-medium text-gray-700 mb-1">
                      Email Address
                    </label>
                    <div className="relative">
                      <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <Mail className="h-5 w-5 text-gray-400" />
                      </div>
                      <input
                        {...field}
                        type="email"
                        placeholder="john@mail.com"
                        className={`block w-full pl-10 pr-3 py-3 border rounded-[10px] outline-none transition
                          ${errors.email ? "border-red-500" : "border-gray-300"}
                          focus:border-brand-navy
                        `}
                      />
                    </div>
                  </div>
                )}
              />
            </Form.Item>

            {/* PASSWORD */}
            {!isForgotPassword && (
              <Form.Item
                validateStatus={errors.password ? "error" : ""}
                help={errors.password?.message}
              >
                <Controller
                  name="password"
                  control={control}
                  render={({ field }) => (
                    <div className="flex flex-col">
                      <label className="text-sm font-medium text-gray-700 mb-1">
                        Password
                      </label>
                      <div className="relative">
                        <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                          <Lock className="h-5 w-5 text-gray-400" />
                        </div>
                        <input
                          {...field}
                          type={showPassword ? "text" : "password"}
                          placeholder="••••••••"
                          className={`block w-full px-10 py-3 border rounded-[10px] outline-none transition
                            ${
                              errors.password
                                ? "border-red-500"
                                : "border-gray-300"
                            }
                            focus:border-brand-navy
                          `}
                        />
                        <button
                          type="button"
                          className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600"
                          onClick={() => setShowPassword(!showPassword)}
                        >
                          {showPassword ? (
                            <EyeOff className="h-5 w-5" />
                          ) : (
                            <Eye className="h-5 w-5" />
                          )}
                        </button>
                      </div>
                    </div>
                  )}
                />
              </Form.Item>
            )}

            {/* Forgot Password */}
            {!isForgotPassword && (
              <div className="flex justify-end">
                <button
                  type="button"
                  className="text-sm font-semibold text-brand-navy"
                  onClick={() => {
                    reset();
                    setForgotPassword(true);
                  }}
                >
                  Forgot password?
                </button>
              </div>
            )}

            {/* SUBMIT BUTTON */}
            <motion.button
              type="submit"
              whileHover={{ scale: 1.03 }}
              whileTap={{ scale: 0.97 }}
              disabled={isSubmitting}
              className={`w-full bg-brand-navy flex items-center justify-center py-3 px-4 rounded-xl shadow-sm text-base font-bold text-white transition
                ${isSubmitting ? "opacity-60 cursor-not-allowed" : ""}
                `}
            >
              {isSubmitting
                ? "Please wait..."
                : isForgotPassword
                ? "Send Reset Link"
                : `Log In`}
              <ArrowRight className="ml-2 w-5 h-5" />
            </motion.button>

            <div className="w-full text-center mt-4 text-sm text-gray-500">
              I don't have an account ?{" "}
              <Link to="/register" className="font-semibold text-brand-navy">
                Register
              </Link>
            </div>

            {/* Back to login */}
            {isForgotPassword && (
              <div className="mt-4 text-center">
                <button
                  type="button"
                  className="text-brand-navy hover:text-brand-orange font-semibold"
                  onClick={() => {
                    reset();
                    setForgotPassword(false);
                  }}
                >
                  ← Back to login
                </button>
              </div>
            )}
          </form>
        </div>
      </motion.div>
    </motion.div>
  );
}
