// Converted to React Hook Form + Yup validation
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { Input, Button, Card, Typography, Spin, Alert, Select } from "antd";
import { motion } from "framer-motion";
import {
  Building,
  Mail,
  User,
  Phone,
  MapPin,
  Lock,
  ArrowRight,
  ArrowLeft,
} from "lucide-react";
import { Link, useNavigate } from "react-router-dom";
import { useState, JSX } from "react";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import toast from "react-hot-toast";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import ROUTE_CONSTANTS from "@/constants/route.constants";
import { indianStateOptions } from "@/types";

const { TextArea } = Input;

export interface IInstitutionRegister {
  institutionName: string;
  email: string;
  contactPerson: string;
  phone: string;
  institutionAddress: string;
  state: string;
  pincode: string;
  password: string;
  confirmPassword: string;
}

// Yup schema
const schema = yup.object().shape({
  institutionName: yup.string().required("Please enter institution name"),
  email: yup.string().email().required("Please enter a valid email"),
  contactPerson: yup.string().required("Please enter contact person name"),
  phone: yup.string().required("Please enter contact number"),
  institutionAddress: yup.string().required("Please enter address"),
  state: yup.string().required("Please enter state"),
  pincode: yup.string().required("Please enter pincode"),
  password: yup
    .string()
    .min(6, "Password must be at least 6 characters")
    .required("Please enter password"),
  confirmPassword: yup
    .string()
    .oneOf([yup.ref("password")], "Passwords do not match")
    .required("Please confirm password"),
});

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

  const resolver = yupResolver(schema);

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm({
    resolver,
    mode: "onChange", // Important for realtime validation
  });

  const onSubmit = async (values: IInstitutionRegister) => {
    const {
      institutionName,
      contactPerson,
      phone,
      email,
      institutionAddress,
      confirmPassword,
      state,
      pincode,
    } = values;

    setLoading(true);

    try {
      const response = await API_Instance.post(
        `${API_Constants.registerInstitution}`,
        {
          institutionName,
          contactPerson,
          phone,
          email,
          institutionAddress,
          password: confirmPassword,
          state,
          pincode,
        },
      );

      toast.success(
        response?.data?.message || "Verification email sent successfully.",
      );
      setSuccess(true);
      reset();
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setLoading(false);
    }
  };

  const formFields: {
    name: keyof IInstitutionRegister;
    label: string;
    icon: JSX.Element;
    placeholder: string;
    type?: string;
    options?: any[];
    controllerRules?: any;
    inputMode?: React.HTMLAttributes<HTMLInputElement>["inputMode"];
    maxLength?: number;
  }[] = [
      {
        name: "institutionName",
        label: "Institution Name",
        icon: <Building size={18} className="text-gray-400" />,
        placeholder: "Enter institution name",
      },
      {
        name: "email",
        label: "Email",
        icon: <Mail size={18} className="text-gray-400" />,
        placeholder: "Enter institution email",
      },
      {
        name: "contactPerson",
        label: "Contact Person Name",
        icon: <User size={18} className="text-gray-400" />,
        placeholder: "Enter Contact person name",
      },
      {
        name: "phone",
        label: "Contact Number",
        icon: <Phone size={18} className="text-gray-400" />,
        placeholder: "+91 98765 43210",
        type: "text",
        inputMode: "numeric",
        maxLength: 10,
        controllerRules: {
          required: "Phone number is required",
          pattern: {
            value: /^[0-9]{10}$/,
            message: "Phone number must be 10 digits",
          },
        },
      },
      {
        name: "institutionAddress",
        label: "Institution Address",
        icon: <MapPin size={18} className="text-gray-400" />,
        placeholder: "Enter institution address",
        type: "textarea",
      },
      {
        name: "pincode",
        label: "Pincode",
        icon: <MapPin size={18} className="text-gray-400" />,
        placeholder: "Enter a pincode",
        type: "text",
        inputMode: "numeric",
        maxLength: 6,
        controllerRules: {
          required: "Pincode is required",
          pattern: {
            value: /^[0-9]{6}$/,
            message: "Pincode must be 6 digits",
          },
        },
      },
      {
        name: "state",
        label: "State",
        icon: <User size={18} className="text-gray-400" />,
        placeholder: "Select state",
        type: "select",
        options: [...indianStateOptions],
      },
      {
        name: "password",
        label: "Password",
        icon: <Lock size={18} className="text-gray-400" />,
        placeholder: "Create a strong password",
        type: "password",
      },
      {
        name: "confirmPassword",
        label: "Confirm Password",
        icon: <Lock size={18} className="text-gray-400" />,
        placeholder: "Re-enter your password",
        type: "password",
      },
    ];

  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
          {formFields.map((field, index) => (
            <motion.div
              key={field.name}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: index * 0.08 }}
              className={field.type === "textarea" ? "md:col-span-2" : ""}
            >
              <label className="text-gray-700 font-medium">{field.label}</label>

              <Controller
                name={field.name}
                control={control}
                rules={field.controllerRules}
                render={({ field: formField }) => (
                  <>
                    {/* PASSWORD */}
                    {field.type === "password" ? (
                      <Input.Password
                        {...formField}
                        placeholder={field.placeholder}
                        prefix={field.icon}
                        className=""
                        style={{ height: "48px" }}
                      />
                    ) : /* TEXTAREA */
                      field.type === "textarea" ? (
                        <TextArea
                          {...formField}
                          rows={3}
                          placeholder={field.placeholder}
                          className=""
                        />
                      ) : /* SELECT */
                        field.type === "select" ? (
                          <Select
                            value={formField.value}
                            onChange={formField.onChange}
                            placeholder={field.placeholder}
                            className="w-full"
                            style={{ height: "48px" }}
                            allowClear
                          >
                            {field.options?.map((o) => (
                              <Select.Option key={o.value} value={o.value}>
                                {o.label}
                              </Select.Option>
                            ))}
                          </Select>
                        ) : (
                          /* INPUT (DEFAULT) */
                          <Input
                            {...formField}
                            type="text"
                            inputMode={field.inputMode}
                            maxLength={field.maxLength}
                            placeholder={field.placeholder}
                            prefix={field.icon}
                            className=""
                            style={{ height: "48px" }}
                            onChange={(e) => {
                              let value = e.target.value;

                              // numeric-only enforcement
                              if (field.inputMode === "numeric") {
                                value = value.replace(/\D/g, "");
                              }

                              formField.onChange(value);
                            }}
                          />
                        )}
                  </>
                )}
              />

              {/* ERROR */}
              {errors[field.name] && (
                <p className="text-red-500 text-sm mt-1">
                  {errors[field.name]?.message as string}
                </p>
              )}
            </motion.div>
          ))}
        </div>

        <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-navy hover:bg-navy-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 you provided."
            type="success"
            showIcon
            className="rounded-xl"
          />
        </motion.div>
      )}
      {success ? (
        <div className="w-full flex justify-center items-center">
          <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>
      ) : (
        <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>
      )}
    </>
  );
}
