import { Card, Input, Button, Typography, Row, Col, Alert } from "antd";
import { motion } from "framer-motion";
import { Lock } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import toast from "react-hot-toast";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import API_Constants from "@/constants/api.constants";
import { useState } from "react";
import { API_Instance } from "@/api/axios.instance";

const { Title, Paragraph, Link } = Typography;

// ✅ Yup schema
const schema = yup.object({
  password: yup
    .string()
    .min(6, "Password must be at least 6 characters")
    .required("Please enter your password"),
  confirmPassword: yup
    .string()
    .oneOf([yup.ref("password")], "Passwords do not match")
    .required("Please confirm your password"),
});

export default function ForgotPassword() {
  const navigate = useNavigate();
  const [success, setSuccess] = useState(false);
  const [loading, setLoading] = useState(false);

  const {
    handleSubmit,
    control,
    formState: { errors },
    reset,
  } = useForm({
    resolver: yupResolver(schema),
    mode: "onBlur",
  });

  const onSubmit = async (values: any) => {
    const { confirmPassword } = values;
    const token = window.location.pathname.split("/").pop();

    if (!token) {
      return;
    }

    setLoading(true);
    try {
      const response = await API_Instance.post(
        `${API_Constants.resetPasswordToken}/${token}`,
        {
          password: confirmPassword,
        },
      );
      toast.success(response?.data?.message || "New password has changed.");
      setSuccess(true);
      reset();
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-pink-100 via-purple-100 to-indigo-100 flex items-center justify-center p-4 py-12">
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ duration: 0.5 }}
        className="w-full max-w-lg"
      >
        {/* Header */}
        <div className="text-center mb-8">
          <motion.div
            initial={{ y: -20 }}
            animate={{ y: 0 }}
            className="flex items-center justify-center space-x-2 mb-4"
          >
            {/* <Award size={40} className="text-pink-600" /> */}
            <span className="text-3xl font-bold bg-gradient-to-r from-pink-600 to-purple-600 bg-clip-text text-transparent">
              ExamInfra
            </span>
          </motion.div>
        </div>

        {/* Card */}
        <Card className="rounded-3xl shadow-2xl border-0 relative overflow-hidden">
          <div className="absolute top-0 right-0 w-40 h-40 bg-gradient-to-br from-pink-400 to-purple-400 rounded-full opacity-10 -mr-20 -mt-20" />
          <div className="absolute bottom-0 left-0 w-32 h-32 bg-gradient-to-tr from-purple-400 to-indigo-400 rounded-full opacity-10 -ml-16 -mb-16" />

          {/* Form */}
          <form
            onSubmit={handleSubmit(onSubmit)}
            className="space-y-4 relative z-10"
          >
            <Title level={4} className="mb-2">
              Forgot Password
            </Title>
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.4 }}
            >
              <label className="text-gray-700 font-medium">New Password</label>
              <Controller
                name="password"
                control={control}
                render={({ field }) => (
                  <Input.Password
                    {...field}
                    prefix={<Lock size={18} />}
                    placeholder="Create a strong password"
                    className="rounded-xl mt-1"
                    style={{ height: "48px" }}
                  />
                )}
              />
              {errors.password && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.password.message}
                </p>
              )}
            </motion.div>
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.5 }}
            >
              <label className="text-gray-700 font-medium">
                Confirm New Password
              </label>
              <Controller
                name="confirmPassword"
                control={control}
                render={({ field }) => (
                  <Input.Password
                    {...field}
                    prefix={<Lock size={18} />}
                    placeholder="Re-enter your password"
                    className="rounded-xl mt-1"
                    style={{ height: "48px" }}
                  />
                )}
              />
              {errors.confirmPassword && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.confirmPassword.message}
                </p>
              )}
            </motion.div>

            {/* Submit Button */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.6 }}
              className="pt-4"
            >
              <motion.div
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
              >
                <Button
                  type="primary"
                  htmlType="submit"
                  block
                  loading={loading}
                  size="large"
                  className="rounded-xl font-semibold"
                  style={{
                    background:
                      "linear-gradient(135deg, #FF6B6B 0%, #9B59B6 100%)",
                    border: "none",
                    height: "52px",
                  }}
                >
                  {loading ? "Changing..." : "Change Password"}
                </Button>
              </motion.div>
            </motion.div>
          </form>

          {success && (
            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3 }}
              className="mt-4 flex flex-col items-center"
            >
              <Alert
                message="Success"
                description="Your password has been changed now you can login with new password"
                type="success"
                showIcon
                className="rounded-xl"
              />
              <a
                href="/login"
                className="hidden mt-6 inline-block bg-green-600 text-white px-6 py-2 rounded-sm md:block"
              >
                Go to Login
              </a>
              <a
                href="examinfra://reset-success"
                className="mt-6 inline-block bg-green-600 text-white px-6 py-2 rounded-sm md:hidden"
              >
                Go to Login
              </a>
            </motion.div>
          )}
        </Card>
      </motion.div>
    </div>
  );
}
