"use client";

import { useState, useRef } from "react";
import Image from "next/image";
import localFont from "next/font/local";
import { useGSAP } from "@gsap/react";
import gsap from "gsap";
import { Envelope, Lock, ShieldCheck, ArrowRight, CircleNotch, Eye, EyeSlash, User, Phone } from "@phosphor-icons/react";
import logo from '../../../public/logo.png';

const figtree = localFont({
    src: [
        {
            path: '../../../public/Fonts/figtree/figtree.ttf',
        },
    ],
});

// Reusing styles for consistency
const inputStyle = `${figtree.className} w-full p-4 border-2 border-black text-lg outline-none focus:bg-[#F7F7F7] transition-colors placeholder:text-gray-400 bg-white`;
const buttonStyle = `${figtree.className} w-full flex items-center justify-center gap-2 px-8 py-4 border-2 border-black bg-[#E7FE78] text-lg font-bold hover:bg-[#dcfc4e] transition-colors disabled:opacity-50 disabled:cursor-not-allowed shadow-[4px_4px_0px_0px_rgba(0,0,0,1)] hover:translate-y-[2px] hover:shadow-[2px_2px_0px_0px_rgba(0,0,0,1)] active:translate-y-[4px] active:shadow-none transition-all`;
const labelStyle = `${figtree.className} text-sm font-bold uppercase tracking-wider mb-2 block`;

const countries = [
    { code: 'PK', name: 'Pakistan', dial_code: '+92' },
    { code: 'US', name: 'United States', dial_code: '+1' },
    { code: 'GB', name: 'United Kingdom', dial_code: '+44' },
    { code: 'CA', name: 'Canada', dial_code: '+1' },
    { code: 'AU', name: 'Australia', dial_code: '+61' },
    { code: 'UAE', name: 'UAE', dial_code: '+971' },
    { code: 'SA', name: 'Saudi Arabia', dial_code: '+966' },
];

function Signup() {
    const [step, setStep] = useState<'details' | 'verification'>('details');
    const [isLoading, setIsLoading] = useState(false);
    const [formData, setFormData] = useState({
        name: '',
        email: '',
        countryCode: '+92',
        phone: '',
        password: '',
        confirmPassword: '',
        emailOtp: '',
        phoneOtp: ''
    });
    const [error, setError] = useState('');
    const [showPassword, setShowPassword] = useState(false);
    const [showConfirmPassword, setShowConfirmPassword] = useState(false);

    const formRef = useRef<HTMLDivElement>(null);
    const imageRef = useRef<HTMLDivElement>(null);

    useGSAP(() => {
        // Animate image side
        gsap.fromTo(imageRef.current,
            { x: -50, opacity: 0 },
            { x: 0, opacity: 1, duration: 1, ease: "power3.out" }
        );

        // Animate form side
        gsap.fromTo(formRef.current,
            { x: 50, opacity: 0 },
            { x: 0, opacity: 1, duration: 1, delay: 0.2, ease: "power3.out" }
        );
    }, []);

    const handleSignup = async (e: React.FormEvent) => {
        e.preventDefault();
        setError('');
        setIsLoading(true);

        // Password validation
        const passwordRegex = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,}$/;

        if (!passwordRegex.test(formData.password)) {
            setError('Password must be at least 8 characters with a number and special character');
            setIsLoading(false);
            return;
        }

        if (formData.password !== formData.confirmPassword) {
            setError('Passwords do not match');
            setIsLoading(false);
            return;
        }

        // Simulate API call
        setTimeout(() => {
            setIsLoading(false);
            if (formData.name && formData.email && formData.phone && formData.password) {
                // Transition to Verification
                gsap.to(formRef.current, {
                    x: -20,
                    opacity: 0,
                    duration: 0.3,
                    onComplete: () => {
                        setStep('verification');
                        gsap.fromTo(formRef.current,
                            { x: 20, opacity: 0 },
                            { x: 0, opacity: 1, duration: 0.3 }
                        );
                    }
                });
            } else {
                setError('Please fill in all fields');
            }
        }, 1000);
    };

    const handleVerify = async (e: React.FormEvent) => {
        e.preventDefault();
        setError('');
        setIsLoading(true);

        // Simulate API call
        setTimeout(() => {
            setIsLoading(false);
            if (formData.emailOtp === '0000' && formData.phoneOtp === '0000') {
                alert('Signup Successful! Account Created.');
                // Here you would redirect or store token
            } else {
                setError('Invalid OTPs. Please try again (Hint: 0000 for both)');
            }
        }, 1000);
    };

    return (
        <div className="flex min-h-screen w-full bg-[#FAFAFA] overflow-hidden">
            {/* Left Side - Visual/Logo */}
            <div className="hidden lg:flex w-1/2 bg-[#E7FE78] border-r-4 border-black flex-col items-center justify-center p-12 relative">
                <div className="absolute inset-0 opacity-10"
                    style={{
                        backgroundImage: `radial-gradient(circle at 2px 2px, black 1px, transparent 0)`,
                        backgroundSize: '32px 32px'
                    }}
                />

                <div ref={imageRef} className="relative z-10 flex flex-col items-center text-center">
                    <div className="w-64 h-64 bg-white border-4 border-black rounded-full flex items-center justify-center mb-12 shadow-[8px_8px_0px_0px_rgba(0,0,0,1)]">
                        <Image
                            src={logo}
                            alt="Logo"
                            width={180}
                            height={180}
                            className="object-contain"
                        />
                    </div>
                    <h1 className={`${figtree.className} text-5xl font-black mb-6 tracking-tight`}>
                        Join Us Today
                    </h1>
                    <p className={`${figtree.className} text-xl font-medium max-w-md leading-relaxed`}>
                        Start Your Journey With Us
                    </p>
                </div>
            </div>

            {/* Right Side - Form */}
            <div className="w-full lg:w-1/2 flex flex-col items-center justify-center p-8 lg:p-24 bg-white relative">
                <div ref={formRef} className="w-full max-w-md">
                    {step === 'details' ? (
                        <>
                            <div className="mb-10">
                                <h2 className={`${figtree.className} text-4xl font-bold mb-3`}>Create Account</h2>
                                <p className={`${figtree.className} text-gray-500 text-lg`}>Enter your details to get started</p>
                            </div>

                            <form onSubmit={handleSignup} className="flex flex-col gap-6">
                                <div>
                                    <label className={labelStyle}>Full Name</label>
                                    <div className="relative">
                                        <input
                                            type="text"
                                            placeholder="Abrar Malik"
                                            className={inputStyle}
                                            value={formData.name}
                                            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                        />
                                        <User className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" size={24} />
                                    </div>
                                </div>

                                <div>
                                    <label className={labelStyle}>Email Address</label>
                                    <div className="relative">
                                        <input
                                            type="email"
                                            placeholder="abrar@example.com"
                                            className={inputStyle}
                                            value={formData.email}
                                            onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                        />
                                        <Envelope className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" size={24} />
                                    </div>
                                </div>

                                <div>
                                    <label className={labelStyle}>Phone Number</label>
                                    <div className="flex gap-2">
                                        <div className="relative w-32 shrink-0">
                                            <select
                                                className={`${inputStyle} pr-8 appearance-none cursor-pointer`}
                                                value={formData.countryCode}
                                                onChange={(e) => setFormData({ ...formData, countryCode: e.target.value })}
                                            >
                                                {countries.map((country) => (
                                                    <option key={`${country.code}-${country.dial_code}`} value={country.dial_code}>
                                                        {country.code} {country.dial_code}
                                                    </option>
                                                ))}
                                            </select>
                                            <div className="absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none">
                                                <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                    <path d="M2.5 4.5L6 8L9.5 4.5" stroke="black" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                                </svg>
                                            </div>
                                        </div>
                                        <div className="relative flex-1">
                                            <input
                                                type="tel"
                                                placeholder="3333576756"
                                                className={inputStyle}
                                                value={formData.phone}
                                                onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                                            />
                                            <Phone className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" size={24} />
                                        </div>
                                    </div>
                                </div>

                                <div>
                                    <label className={labelStyle}>Password</label>
                                    <div className="relative">
                                        <input
                                            type={showPassword ? "text" : "password"}
                                            placeholder="••••••••"
                                            className={inputStyle}
                                            value={formData.password}
                                            onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                                        />
                                        <button
                                            type="button"
                                            onClick={() => setShowPassword(!showPassword)}
                                            className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                                        >
                                            {showPassword ? <EyeSlash size={24} /> : <Eye size={24} />}
                                        </button>
                                    </div>
                                    <p className={`${figtree.className} text-xs text-gray-400 mt-1`}>
                                        Min. 8 characters, 1 number, 1 special character
                                    </p>
                                </div>

                                <div>
                                    <label className={labelStyle}>Confirm Password</label>
                                    <div className="relative">
                                        <input
                                            type={showConfirmPassword ? "text" : "password"}
                                            placeholder="••••••••"
                                            className={inputStyle}
                                            value={formData.confirmPassword}
                                            onChange={(e) => setFormData({ ...formData, confirmPassword: e.target.value })}
                                        />
                                        <button
                                            type="button"
                                            onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                                            className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                                        >
                                            {showConfirmPassword ? <EyeSlash size={24} /> : <Eye size={24} />}
                                        </button>
                                    </div>
                                </div>

                                {error && (
                                    <div className={`${figtree.className} p-4 bg-red-50 border-2 border-red-500 text-red-500 font-bold flex items-center gap-2`}>
                                        <ShieldCheck size={20} />
                                        {error}
                                    </div>
                                )}

                                <button
                                    type="submit"
                                    disabled={isLoading}
                                    className={buttonStyle}
                                >
                                    {isLoading ? (
                                        <CircleNotch className="animate-spin" size={24} />
                                    ) : (
                                        <>Sign Up <ArrowRight size={20} weight="bold" /></>
                                    )}
                                </button>

                                <div className="text-center mt-4">
                                    <p className={`${figtree.className} text-gray-500`}>
                                        Already have an account?{' '}
                                        <a href="/login" className="text-black font-bold hover:underline">
                                            Log in
                                        </a>
                                    </p>
                                </div>
                            </form>
                        </>
                    ) : (
                        <>
                            <div className="mb-10">
                                <h2 className={`${figtree.className} text-4xl font-bold mb-3`}>Verify Account</h2>
                                <p className={`${figtree.className} text-gray-500 text-lg`}>Enter the codes sent to your email and phone</p>
                            </div>

                            <form onSubmit={handleVerify} className="flex flex-col gap-6">
                                <div>
                                    <label className={labelStyle}>Email OTP</label>
                                    <div className="relative">
                                        <input
                                            type="text"
                                            placeholder="0000"
                                            maxLength={4}
                                            className={`${inputStyle} text-center text-2xl tracking-[0.5em] font-bold`}
                                            value={formData.emailOtp}
                                            onChange={(e) => setFormData({ ...formData, emailOtp: e.target.value })}
                                        />
                                        <Envelope className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" size={24} />
                                    </div>
                                </div>

                                <div>
                                    <label className={labelStyle}>Phone OTP</label>
                                    <div className="relative">
                                        <input
                                            type="text"
                                            placeholder="0000"
                                            maxLength={4}
                                            className={`${inputStyle} text-center text-2xl tracking-[0.5em] font-bold`}
                                            value={formData.phoneOtp}
                                            onChange={(e) => setFormData({ ...formData, phoneOtp: e.target.value })}
                                        />
                                        <Phone className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" size={24} />
                                    </div>
                                    <p className={`${figtree.className} text-xs text-gray-400 mt-2 text-center`}>Use '0000' for testing both</p>
                                </div>

                                {error && (
                                    <div className={`${figtree.className} p-4 bg-red-50 border-2 border-red-500 text-red-500 font-bold flex items-center gap-2`}>
                                        <ShieldCheck size={20} />
                                        {error}
                                    </div>
                                )}

                                <button
                                    type="submit"
                                    disabled={isLoading}
                                    className={buttonStyle}
                                >
                                    {isLoading ? (
                                        <CircleNotch className="animate-spin" size={24} />
                                    ) : (
                                        <>Verify & Create Account <ShieldCheck size={20} weight="bold" /></>
                                    )}
                                </button>

                                <button
                                    type="button"
                                    onClick={() => {
                                        setStep('details');
                                        setError('');
                                    }}
                                    className={`${figtree.className} text-gray-500 hover:text-black hover:underline text-center mt-4`}
                                >
                                    Back to Details
                                </button>
                            </form>
                        </>
                    )}
                </div>
            </div>
        </div>
    );
}

export default Signup;
