import { Input, Row, Col, Alert } from "antd";
import { motion } from "framer-motion";
import { User, Mail, Phone, Lock, ArrowRight, ArrowLeft } from "lucide-react";
import { Link, useNavigate } from "react-router-dom";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import axios from "axios";
import toast from "react-hot-toast";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import API_Constants from "@/constants/api.constants";
import ROUTE_CONSTANTS from "@/constants/route.constants";
import { useState } from "react";

const schema = yup.object({
  firstName: yup.string().required("Please enter your first name"),
  lastName: yup.string().required("Please enter your last name"),
  email: yup
    .string()
    .email("Please enter a valid email")
    .required("Please enter your email"),
  phone: yup
    .string()
    .matches(/^[0-9]{10}$/, "Please enter a valid 10-digit phone number")
    .required("Please enter your phone number"),
  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 StudentRegister() {
  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 { firstName, lastName, phone, email, confirmPassword } = values;
    setLoading(true);
    try {
      const response = await axios.post(
        `/api${API_Constants.registerStudent}`,
        {
          firstName,
          lastName,
          phone,
          email,
          password: confirmPassword,
        },
      );
      toast.success(
        response?.data?.message || "Verification email sended on email.",
      );
      setSuccess(true);
      reset();
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="mt-4">
      <form
        onSubmit={handleSubmit(onSubmit)}
        className="space-y-4 relative z-10"
      >
        <Row gutter={16}>
          {/* First Name */}
          <Col xs={24} sm={12}>
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0 }}
            >
              <label className="text-gray-700 font-medium">First Name</label>
              <Controller
                name="firstName"
                control={control}
                render={({ field }) => (
                  <Input
                    {...field}
                    prefix={<User size={18} />}
                    placeholder="John"
                    className="rounded-xl mt-1"
                    style={{ height: "48px" }}
                  />
                )}
              />
              {errors.firstName && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.firstName.message}
                </p>
              )}
            </motion.div>
          </Col>

          {/* Last Name */}
          <Col xs={24} sm={12}>
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.1 }}
            >
              <label className="text-gray-700 font-medium">Last Name</label>
              <Controller
                name="lastName"
                control={control}
                render={({ field }) => (
                  <Input
                    {...field}
                    prefix={<User size={18} />}
                    placeholder="Doe"
                    className="rounded-xl mt-1"
                    style={{ height: "48px" }}
                  />
                )}
              />
              {errors.lastName && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.lastName.message}
                </p>
              )}
            </motion.div>
          </Col>
        </Row>

        <Row gutter={16}>
          {/* Email */}
          <Col xs={24} sm={12}>
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.2 }}
            >
              <label className="text-gray-700 font-medium">Email</label>
              <Controller
                name="email"
                control={control}
                render={({ field }) => (
                  <Input
                    {...field}
                    prefix={<Mail size={18} />}
                    placeholder="john@mail.com"
                    className="rounded-xl mt-1"
                    style={{ height: "48px" }}
                  />
                )}
              />
              {errors.email && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.email.message}
                </p>
              )}
            </motion.div>
          </Col>

          {/* Phone */}
          <Col xs={24} sm={12}>
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.3 }}
            >
              <label className="text-gray-700 font-medium">Phone</label>
              <Controller
                name="phone"
                control={control}
                render={({ field }) => (
                  <Input
                    {...field}
                    prefix={<Phone size={18} />}
                    placeholder="9876543210"
                    className="rounded-xl mt-1"
                    style={{ height: "48px" }}
                  />
                )}
              />
              {errors.phone && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.phone.message}
                </p>
              )}
            </motion.div>
          </Col>
        </Row>

        <Row gutter={16}>
          {/* Password */}
          <Col xs={24} sm={12}>
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.4 }}
            >
              <label className="text-gray-700 font-medium">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>
          </Col>

          {/* Confirm Password */}
          <Col xs={24} sm={12}>
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.5 }}
            >
              <label className="text-gray-700 font-medium">
                Confirm 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>
          </Col>
        </Row>

        <motion.button
          type="submit"
          whileHover={{ scale: 1.03 }}
          whileTap={{ scale: 0.97 }}
          disabled={loading}
          className={`w-full !mt-10 py-3 px-4 rounded-xl shadow-md text-white font-bold transition
            ${"bg-brand-green hover:bg-green-600"}
            ${loading && "opacity-50 cursor-not-allowed"}
          `}
        >
          {loading ? "Registering..." : "Create Account"}
          <ArrowRight className="ml-2 inline w-5 h-5" />
        </motion.button>
        <p className="text-xs text-center text-gray-500 mt-4">
          By clicking Create Account, you agree to our{" "}
          <Link
            to={ROUTE_CONSTANTS.Terms}
            className="text-brand-navy font-semibold underline"
          >
            Terms & Conditions
          </Link>{" "}
          and{" "}
          <Link
            to={ROUTE_CONSTANTS.Privacy}
            className="text-brand-navy font-semibold underline"
          >
            Privacy Policy
          </Link>
          .
        </p>
      </form>

      {success && (
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
          className="mt-4"
        >
          <Alert
            message="Success"
            description="A verification email has been sent to the email address you provided."
            type="success"
            showIcon
            className="rounded-xl"
          />
        </motion.div>
      )}

      {success ? (
        <Link to="/login" className={`mt-4 mx-auto text-lg font-semibold`}>
          <ArrowLeft className="mr-2 inline w-5 h-5" />
          Goto Login
        </Link>
      ) : (
        <div className="w-full text-center mt-4 text-sm text-gray-500">
          I already have an account ?{" "}
          <Link to="/login" className="font-semibold text-brand-navy">
            Login
          </Link>
        </div>
      )}
    </div>
  );
}
