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

interface LoginPageProps {
    onSwitchToSignUp?: () => void;
}

export default function LoginPage({ onSwitchToSignUp }: LoginPageProps) {
    const [identifier, setIdentifier] = useState('');
    const [password, setPassword] = useState('');
    const [localError, setLocalError] = useState('');
    const [submitting, setSubmitting] = useState(false);
    const [isForgotPassword, setIsForgotPassword] = useState(false);
    const [resetEmail, setResetEmail] = useState('');
    const login = useAuthStore((s) => s.login);

    const handleSubmit = async (e: FormEvent) => {
        e.preventDefault();
        if (!identifier.trim() || !password) {
            setLocalError('Please enter both username and password.');
            return;
        }
        setLocalError('');
        setSubmitting(true);
        try {
            await login(identifier.trim(), password);
        } catch (err: unknown) {
            const msg = err instanceof Error ? err.message : 'Login failed';
            if (msg === 'InvalidCredentials') {
                setLocalError('Invalid username or password.');
            } else if (msg === 'InactiveUser') {
                setLocalError('Your account is currently inactive. Please contact support.');
            } else {
                setLocalError(msg);
            }
        } finally {
            setSubmitting(false);
        }
    };

    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">
                        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">
                        {isForgotPassword ? 'Reset your password' : 'Sign in to your account'}
                    </h2>

                    {localError && !isForgotPassword && (
                        <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>
                    )}

                    {!isForgotPassword ? (
                        <>
                            <form onSubmit={handleSubmit} className="space-y-5">
                                {/* Username / Email */}
                                <div>
                                    <label
                                        htmlFor="login-identifier"
                                        className="block text-sm font-medium text-gray-700 mb-1.5"
                                    >
                                        Username or Email
                                    </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="login-identifier"
                                            type="text"
                                            value={identifier}
                                            onChange={(e) => setIdentifier(e.target.value)}
                                            placeholder="Enter your username or email"
                                            autoComplete="username"
                                            className="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"
                                        />
                                    </div>
                                </div>

                                {/* Password */}
                                <div>
                                    <label
                                        htmlFor="login-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="login-password"
                                            type="password"
                                            value={password}
                                            onChange={(e) => setPassword(e.target.value)}
                                            placeholder="Enter your password"
                                            autoComplete="current-password"
                                            className="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"
                                        />
                                    </div>
                                </div>

                                {/* Submit */}
                                <button
                                    id="login-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>
                                            Signing in…
                                        </span>
                                    ) : (
                                        'Sign In'
                                    )}
                                </button>
                            </form>
                            <div className="mt-4 text-center">
                                <button
                                    type="button"
                                    onClick={() => setIsForgotPassword(true)}
                                    className="text-sm text-primary hover:underline focus:outline-none"
                                >
                                    Forgot password?
                                </button>
                            </div>
                        </>
                    ) : (
                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                alert(`Password reset link sent to ${resetEmail}`);
                                setIsForgotPassword(false);
                            }}
                            className="space-y-5"
                        >
                            <div>
                                <label
                                    htmlFor="reset-email"
                                    className="block text-sm font-medium text-gray-700 mb-1.5"
                                >
                                    Email
                                </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="reset-email"
                                        type="email"
                                        value={resetEmail}
                                        onChange={(e) => setResetEmail(e.target.value)}
                                        placeholder="Enter your email"
                                        required
                                        className="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"
                                    />
                                </div>
                            </div>
                            <button
                                type="submit"
                                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"
                            >
                                Reset Password
                            </button>
                            <div className="mt-4 text-center">
                                <button
                                    type="button"
                                    onClick={() => setIsForgotPassword(false)}
                                    className="text-sm text-primary hover:underline focus:outline-none"
                                >
                                    Back to login
                                </button>
                            </div>
                        </form>
                    )}
                </div>

                {onSwitchToSignUp && (
                    <div className="mt-6 text-center">
                        <p className="text-sm text-gray-500">
                            Don't have an account?{' '}
                            <button
                                type="button"
                                onClick={onSwitchToSignUp}
                                className="text-primary font-medium hover:underline focus:outline-none"
                            >
                                Create an account
                            </button>
                        </p>
                    </div>
                )}

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