import { useState, type FormEvent } from 'react';
import { useAuthStore } from '../store/useAuthStore';
import { Heart, Lock, User, Mail, AlertCircle, UserPlus, Stethoscope } from 'lucide-react';

interface SignUpPageProps {
    onSwitchToLogin: () => void;
}

export default function SignUpPage({ onSwitchToLogin }: SignUpPageProps) {
    const [dispName, setDispName] = useState('');
    const [username, setUsername] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [role, setRole] = useState<'patient' | 'practitioner'>('patient');
    const [localError, setLocalError] = useState('');
    const [submitting, setSubmitting] = useState(false);
    const register = useAuthStore((s) => s.register);

    const handleSubmit = async (e: FormEvent) => {
        e.preventDefault();
        if (!dispName.trim() || !username.trim() || !email.trim() || !password || !confirmPassword) {
            setLocalError('Please fill in all fields.');
            return;
        }
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email.trim())) {
            setLocalError('Please enter a valid email address.');
            return;
        }
        if (username.trim().length < 4) {
            setLocalError('Username must be at least 4 characters long.');
            return;
        }
        if (password.length < 8) {
            setLocalError('Password must be at least 8 characters.');
            return;
        }
        if (password !== confirmPassword) {
            setLocalError('Passwords do not match.');
            return;
        }
        setLocalError('');
        setSubmitting(true);
        try {
            await register({
                dispName: dispName.trim(),
                username: username.trim(),
                email: email.trim(),
                password,
                role,
            });
        } catch (err: unknown) {
            const msg = err instanceof Error ? err.message : 'Registration failed';
            if (msg === 'EmailAlreadyExists') {
                setLocalError('An account with this email already exists.');
            } else if (msg === 'UsernameAlreadyExists') {
                setLocalError('This username is already taken.');
            } else if (msg === 'WeakPassword') {
                setLocalError('Password must be at least 8 characters.');
            } else if (msg === 'ValidationError') {
                setLocalError('Validation error. Please ensure your email is formatted correctly and fields meet requirements.');
            } else {
                setLocalError(msg);
            }
        } finally {
            setSubmitting(false);
        }
    };

    const inputClass =
        'w-full pl-10 pr-4 py-2.5 rounded-lg border border-gray-200 bg-gray-50/50 text-gray-900 placeholder:text-gray-400 text-sm focus:ring-2 focus:ring-primary/40 focus:border-primary transition-all duration-200';

    return (
        <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 via-blue-50 to-teal-50 relative overflow-hidden">
            {/* Background decorations */}
            <div className="absolute inset-0 pointer-events-none">
                <div className="absolute -top-24 -right-24 w-96 h-96 rounded-full bg-primary/5 blur-3xl" />
                <div className="absolute -bottom-32 -left-32 w-[28rem] h-[28rem] rounded-full bg-secondary/10 blur-3xl" />
                <div className="absolute top-1/3 right-1/4 w-64 h-64 rounded-full bg-accent/5 blur-2xl" />
            </div>

            <div className="relative z-10 w-full max-w-md px-6">
                {/* Logo / Brand */}
                <div className="text-center mb-8">
                    <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-gradient-to-br from-primary to-secondary shadow-lg shadow-primary/25 mb-4">
                        <Heart className="w-8 h-8 text-white" />
                    </div>
                    <h1 className="text-3xl font-bold text-gray-900 tracking-tight">
                        Hipograf
                    </h1>
                    <p className="mt-1 text-gray-500 text-sm">
                        Create your personal health dashboard
                    </p>
                </div>

                {/* Card */}
                <div className="bg-white/80 backdrop-blur-xl rounded-2xl shadow-xl shadow-gray-200/50 border border-white/60 p-8">
                    <h2 className="text-xl font-semibold text-gray-900 mb-6">
                        Create your account
                    </h2>

                    {localError && (
                        <div className="flex items-center gap-2 mb-4 p-3 rounded-lg bg-red-50 border border-red-100 text-red-600 text-sm">
                            <AlertCircle className="w-4 h-4 flex-shrink-0" />
                            <span>{localError}</span>
                        </div>
                    )}

                    <form onSubmit={handleSubmit} className="space-y-4">
                        {/* Display Name */}
                        <div>
                            <label
                                htmlFor="signup-dispname"
                                className="block text-sm font-medium text-gray-700 mb-1.5"
                            >
                                Display Name
                            </label>
                            <div className="relative">
                                <UserPlus className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                                <input
                                    id="signup-dispname"
                                    type="text"
                                    value={dispName}
                                    onChange={(e) => setDispName(e.target.value)}
                                    placeholder="Your full name"
                                    autoComplete="name"
                                    className={inputClass}
                                />
                            </div>
                        </div>

                        {/* Username */}
                        <div>
                            <label
                                htmlFor="signup-username"
                                className="block text-sm font-medium text-gray-700 mb-1.5"
                            >
                                Username
                            </label>
                            <div className="relative">
                                <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                                <input
                                    id="signup-username"
                                    type="text"
                                    value={username}
                                    onChange={(e) => setUsername(e.target.value)}
                                    placeholder="Choose a username"
                                    autoComplete="username"
                                    className={inputClass}
                                />
                            </div>
                        </div>

                        {/* Email */}
                        <div>
                            <label
                                htmlFor="signup-email"
                                className="block text-sm font-medium text-gray-700 mb-1.5"
                            >
                                Email
                            </label>
                            <div className="relative">
                                <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                                <input
                                    id="signup-email"
                                    type="email"
                                    value={email}
                                    onChange={(e) => setEmail(e.target.value)}
                                    placeholder="you@example.com"
                                    autoComplete="email"
                                    className={inputClass}
                                />
                            </div>
                        </div>

                        {/* Password */}
                        <div>
                            <label
                                htmlFor="signup-password"
                                className="block text-sm font-medium text-gray-700 mb-1.5"
                            >
                                Password
                            </label>
                            <div className="relative">
                                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                                <input
                                    id="signup-password"
                                    type="password"
                                    value={password}
                                    onChange={(e) => setPassword(e.target.value)}
                                    placeholder="At least 8 characters"
                                    autoComplete="new-password"
                                    className={inputClass}
                                />
                            </div>
                        </div>

                        {/* Confirm Password */}
                        <div>
                            <label
                                htmlFor="signup-confirm"
                                className="block text-sm font-medium text-gray-700 mb-1.5"
                            >
                                Confirm Password
                            </label>
                            <div className="relative">
                                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                                <input
                                    id="signup-confirm"
                                    type="password"
                                    value={confirmPassword}
                                    onChange={(e) => setConfirmPassword(e.target.value)}
                                    placeholder="Re-enter your password"
                                    autoComplete="new-password"
                                    className={inputClass}
                                />
                            </div>
                        </div>

                        {/* Role Selection */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1.5">
                                I am a
                            </label>
                            <div className="grid grid-cols-2 gap-3">
                                <button
                                    type="button"
                                    onClick={() => setRole('patient')}
                                    className={`flex items-center justify-center gap-2 py-2.5 rounded-lg border text-sm font-medium transition-all duration-200 ${
                                        role === 'patient'
                                            ? 'border-primary bg-primary/10 text-primary ring-2 ring-primary/30'
                                            : 'border-gray-200 bg-gray-50/50 text-gray-600 hover:border-gray-300'
                                    }`}
                                >
                                    <Heart className="w-4 h-4" />
                                    Patient
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setRole('practitioner')}
                                    className={`flex items-center justify-center gap-2 py-2.5 rounded-lg border text-sm font-medium transition-all duration-200 ${
                                        role === 'practitioner'
                                            ? 'border-primary bg-primary/10 text-primary ring-2 ring-primary/30'
                                            : 'border-gray-200 bg-gray-50/50 text-gray-600 hover:border-gray-300'
                                    }`}
                                >
                                    <Stethoscope className="w-4 h-4" />
                                    Practitioner
                                </button>
                            </div>
                        </div>

                        {/* Submit */}
                        <button
                            id="signup-submit"
                            type="submit"
                            disabled={submitting}
                            className="w-full py-2.5 rounded-lg font-medium text-white text-sm
                         bg-gradient-to-r from-primary to-primary/90
                         hover:shadow-lg hover:shadow-primary/25 hover:-translate-y-0.5
                         active:translate-y-0
                         transition-all duration-300
                         disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:translate-y-0 disabled:hover:shadow-none"
                        >
                            {submitting ? (
                                <span className="flex items-center justify-center gap-2">
                                    <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                                    </svg>
                                    Creating account…
                                </span>
                            ) : (
                                'Create Account'
                            )}
                        </button>
                    </form>

                    {/* Switch to login */}
                    <div className="mt-6 text-center">
                        <p className="text-sm text-gray-500">
                            Already have an account?{' '}
                            <button
                                type="button"
                                onClick={onSwitchToLogin}
                                className="text-primary font-medium hover:underline focus:outline-none"
                            >
                                Sign in
                            </button>
                        </p>
                    </div>
                </div>

                {/* Footer hint */}
                <p className="text-center text-xs text-gray-400 mt-6">
                    Medical records are encrypted and stored securely.
                </p>
            </div>
        </div>
    );
}
