"use client";

import { useState } from "react";
import { apiCall } from "@/utils/callApi";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { toast } from "sonner";

export default function RegisterPage() {
  const router = useRouter();

  const [form, setForm] = useState({
    name: "",
    email: "",
    phone: "",
    password: "",
    confirmPassword: "",
  });

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(false);
  const [agreeTerms, setAgreeTerms] = useState(false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setForm((prev) => ({
      ...prev,
      [e.target.name]: e.target.value,
    }));

    setErrors((prev) => ({
      ...prev,
      [e.target.name]: "",
    }));
  };

  const validate = () => {
    const newErrors: Record<string, string> = {};

    // Name
    if (!form.name.trim()) {
      newErrors.name = "Name is required";
    } else if (form.name.trim().length < 3) {
      newErrors.name = "Name must be at least 3 characters";
    }

    // Email
    if (!form.email.trim()) {
      newErrors.email = "Email is required";
    } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(form.email)) {
      newErrors.email = "Please enter a valid email address";
    }

    // Phone
    if (!form.phone.trim()) {
      newErrors.phone = "Phone number is required";
    } else if (!/^[0-9]{10}$/.test(form.phone)) {
      newErrors.phone = "Phone number must be 10 digits";
    }

    // Password
    if (!form.password) {
      newErrors.password = "Password is required";
    } else if (form.password.length < 6) {
      newErrors.password = "Password must be at least 6 characters";
    }

    // Confirm Password
    if (!form.confirmPassword) {
      newErrors.confirmPassword = "Confirm password is required";
    } else if (form.password !== form.confirmPassword) {
      newErrors.confirmPassword = "Passwords do not match";
    }

    // Terms agreement
    if (!agreeTerms) {
      newErrors.terms = "You must agree to the Terms of Service and Privacy Policy";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validate()) {
      return;
    }

    try {
      setLoading(true);

      const payload = {
        name: form.name.trim(),
        email: form.email.trim(),
        phone: form.phone.trim(),
        password: form.password,
      };

      const res = await apiCall<any>("/clientapi/register", {
        method: "POST",
        body: payload,
      });

      if (res?.data?.success) {
        toast.success("Registration successful! Please login.");
        router.push("/login");
      } else {
        toast.error(res?.data?.message || res?.error || "Registration failed");
      }
    } catch (error: any) {
      toast.error(error?.message || error?.response?.data?.message || "Registration failed");
    } finally {
      setLoading(false);
    }
  };

  return (
    <section className="py-6 md:py-10 2xl:py-16">
      <div className="container container-xxl px-3 mx-auto">
        <div className="flex flex-wrap -mx-2 justify-center">
          <div className="2xl:w-9/12 xl:w-9/12 lg:w-10/12 md:w-full sm:w-full w-full px-2">
            <div className="w-full bg-white shadow-xl overflow-hidden rounded-xl">
              <div className="grid md:grid-cols-2">
                
                {/* Left Section - Registration Form */}
                <div className="px-4 py-4 sm:px-8 sm:py-8 md:px-10 md:py-12 xl:px-10 xl:py-10 flex flex-col justify-center">
                  <h2 className="text-2xl md:text-4xl 2xl:text-5xl font-bold text-gray-800 text-center mb-2 lg:mb-4">
                    Register
                  </h2>
                  
                  <form onSubmit={handleSubmit} className="space-y-4">
                    {/* Name */}
                    <div className="form-group">
                      <label className="block text-sm md:text-sm 2xl:text-lg font-medium text-gray-700 mb-1">
                        Name <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        name="name"
                        value={form.name}
                        onChange={handleChange}
                        placeholder="Enter full name"
                        className={`form-control h-[38px] md:h-[40px] lg:h-[42px] 2xl:h-[48px] text-xs lg:text-sm 2xl:text-lg w-full border rounded-lg px-3 focus:outline-none focus:ring-2 focus:ring-primary ${
                          errors.name ? 'border-red-500' : 'border-gray-300'
                        }`}
                      />
                      {errors.name && (
                        <p className="text-red-500 text-xs mt-1">{errors.name}</p>
                      )}
                    </div>
                    
                    {/* Email */}
                    <div className="form-group">
                      <label className="block text-sm md:text-sm 2xl:text-lg font-medium text-gray-700 mb-1">
                        Email Address <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="email"
                        name="email"
                        value={form.email}
                        onChange={handleChange}
                        placeholder="Enter email"
                        className={`form-control h-[38px] md:h-[40px] lg:h-[42px] 2xl:h-[48px] text-xs lg:text-sm 2xl:text-lg w-full border rounded-lg px-3 focus:outline-none focus:ring-2 focus:ring-primary ${
                          errors.email ? 'border-red-500' : 'border-gray-300'
                        }`}
                      />
                      {errors.email && (
                        <p className="text-red-500 text-xs mt-1">{errors.email}</p>
                      )}
                    </div>
                    
                    {/* Phone */}
                    <div className="form-group">
                      <label className="block text-sm md:text-sm 2xl:text-lg font-medium text-gray-700 mb-1">
                        Phone Number <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="tel"
                        name="phone"
                        value={form.phone}
                        onChange={handleChange}
                        placeholder="Enter phone number"
                        maxLength={10}
                        className={`form-control h-[38px] md:h-[40px] lg:h-[42px] 2xl:h-[48px] text-xs lg:text-sm 2xl:text-lg w-full border rounded-lg px-3 focus:outline-none focus:ring-2 focus:ring-primary ${
                          errors.phone ? 'border-red-500' : 'border-gray-300'
                        }`}
                      />
                      {errors.phone && (
                        <p className="text-red-500 text-xs mt-1">{errors.phone}</p>
                      )}
                    </div>

                    {/* Password */}
                    <div className="form-group">
                      <label className="block text-sm md:text-sm 2xl:text-lg font-medium text-gray-700 mb-1">
                        Password <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="password"
                        name="password"
                        value={form.password}
                        onChange={handleChange}
                        placeholder="Enter password"
                        className={`form-control h-[38px] md:h-[40px] lg:h-[42px] 2xl:h-[48px] text-xs lg:text-sm 2xl:text-lg w-full border rounded-lg px-3 focus:outline-none focus:ring-2 focus:ring-primary ${
                          errors.password ? 'border-red-500' : 'border-gray-300'
                        }`}
                      />
                      {errors.password && (
                        <p className="text-red-500 text-xs mt-1">{errors.password}</p>
                      )}
                    </div>

                    {/* Confirm Password */}
                    <div className="form-group">
                      <label className="block text-sm md:text-sm 2xl:text-lg font-medium text-gray-700 mb-1">
                        Confirm Password <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="password"
                        name="confirmPassword"
                        value={form.confirmPassword}
                        onChange={handleChange}
                        placeholder="Confirm password"
                        className={`form-control h-[38px] md:h-[40px] lg:h-[42px] 2xl:h-[48px] text-xs lg:text-sm 2xl:text-lg w-full border rounded-lg px-3 focus:outline-none focus:ring-2 focus:ring-primary ${
                          errors.confirmPassword ? 'border-red-500' : 'border-gray-300'
                        }`}
                      />
                      {errors.confirmPassword && (
                        <p className="text-red-500 text-xs mt-1">{errors.confirmPassword}</p>
                      )}
                    </div>
                
                    {/* Terms and Conditions */}
                    {errors.terms && (
                      <p className="text-red-500 text-xs mt-1">{errors.terms}</p>
                    )}
                    
                    {/* Sign Up Button */}
                    <button
                      type="submit"
                      disabled={loading}
                      className="w-full theme-btn h-[38px] md:h-[40px] lg:h-[42px] 2xl:h-[48px] bg-primary text-white rounded-lg hover:bg-primary-dark transition disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {loading ? (
                        <span className="flex items-center justify-center gap-2">
                          <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                          </svg>
                          Creating Account...
                        </span>
                      ) : (
                        "Sign Up"
                      )}
                    </button>
                  </form>
                </div>
                
                {/* Right Section - Welcome Back */}
                <div className="bg-[linear-gradient(to_bottom_right,#dda16b,#dda16ba6,#dda16b)] text-white flex flex-col justify-center items-center px-6 py-6 sm:px-8 sm:py-12 lg:px-10 lg:py-16 text-center">
                  <h1 className="text-2xl md:text-4xl 3xl:text-5xl font-bold mb-2 lg:mb-4">
                    Welcome Back!
                  </h1>
                  <p className="text-sm md:text-base lg:text-lg 2xl:text-xl leading-relaxed max-w-sm mb-4 lg:mb-8">
                    Enter your credentials to access your account.
                  </p>
                  <Link href="/login" className="default-btn inline-block px-6 py-2 bg-white text-primary rounded-lg hover:bg-gray-100 transition">
                    Sign In
                  </Link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}