import { useState } from 'react';
import { useNavigate } from 'react-router';
import { useAuth } from '@/providers/auth-provider';
import { Button } from '@/components/base/buttons/button';
import { SocialButton } from '@/components/base/buttons/social-button';
import { Input } from '@/components/base/input/input';

const features = [
    {
        title: 'Unified Lead Inbox',
        description: 'All channels in one workspace',
    },
    {
        title: 'Campaign Intelligence',
        description: 'Real-time performance tracking',
    },
    {
        title: 'Speed to Contact',
        description: 'Automated assignment and outreach',
    },
];


export const LoginPage = () => {
    const { loginWithUser } = useAuth();
    const navigate = useNavigate();

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState<string | null>(null);
    const [isLoading, setIsLoading] = useState(false);

    const handleSubmit = async (event: React.FormEvent) => {
        event.preventDefault();
        setError(null);

        if (!email || !password) {
            setError('Email and password are required');
            return;
        }

        setIsLoading(true);
        try {
            const { apiClient } = await import('@/lib/api-client');
            const response = await apiClient.login(email, password);

            // Build user from sidecar response
            const u = response.user;
            const firstName = u?.firstName ?? '';
            const lastName = u?.lastName ?? '';
            const name = `${firstName} ${lastName}`.trim() || email;
            const initials = `${firstName[0] ?? ''}${lastName[0] ?? ''}`.toUpperCase() || email[0].toUpperCase();

            loginWithUser({
                id: u?.id,
                name,
                initials,
                role: (u?.role ?? 'executive') as 'executive' | 'admin' | 'cc-agent',
                email: u?.email ?? email,
                avatarUrl: u?.avatarUrl,
                platformRoles: u?.platformRoles,
            });

            navigate('/');
        } catch (err: any) {
            setError(err.message);
            setIsLoading(false);
        }
    };

    const handleGoogleSignIn = () => {
        setError('Google sign-in not yet configured');
    };

    return (
        <div className="flex h-screen w-full overflow-hidden">
            {/* Left panel — 60% — hidden on mobile */}
            <div
                className="relative hidden lg:flex flex-col justify-center items-center bg-brand-section overflow-hidden"
                style={{ flex: '0 0 60%' }}
            >
                {/* Abstract corner gradients */}
                <div
                    className="pointer-events-none absolute -top-24 -left-24 size-[400px] rounded-full"
                    style={{
                        background:
                            'radial-gradient(circle, rgba(var(--color-brand-600-rgb, 99,102,241), 0.2) 0%, transparent 70%)',
                        filter: 'blur(200px)',
                    }}
                    aria-hidden="true"
                />
                <div
                    className="pointer-events-none absolute -bottom-24 -right-24 size-[400px] rounded-full"
                    style={{
                        background:
                            'radial-gradient(circle, rgba(var(--color-blue-light-600-rgb, 56,189,248), 0.2) 0%, transparent 70%)',
                        filter: 'blur(200px)',
                    }}
                    aria-hidden="true"
                />

                {/* Content */}
                <div className="relative z-10 flex flex-col gap-10 w-full max-w-[560px] px-12">
                    {/* Logo lockup */}
                    <div className="flex items-center gap-3">
                        <div className="flex items-center justify-center bg-brand-solid rounded-xl p-2 size-10 shrink-0">
                            <span className="text-white font-bold text-lg leading-none font-display">H</span>
                        </div>
                        <span className="text-white font-bold text-xl font-display tracking-tight">Helix Engage</span>
                    </div>

                    {/* Headline */}
                    <div className="flex flex-col gap-4">
                        <h1 className="text-display-md font-bold text-white tracking-tight font-display leading-tight">
                            Smarter lead management for healthcare teams.
                        </h1>
                        <p className="text-lg text-white/70">
                            Unified visibility into leads, campaigns, and team performance. Built for Global Hospital.
                        </p>
                    </div>

                    {/* Feature cards */}
                    <div className="flex flex-col gap-3">
                        {features.map((feature) => (
                            <div
                                key={feature.title}
                                className="flex flex-col gap-1 rounded-2xl p-4 backdrop-blur-sm"
                                style={{ background: 'rgba(255,255,255,0.05)' }}
                            >
                                <span className="text-sm font-semibold text-white">{feature.title}</span>
                                <span className="text-sm" style={{ color: 'rgba(255,255,255,0.6)' }}>{feature.description}</span>
                            </div>
                        ))}
                    </div>
                </div>
            </div>

            {/* Right panel — 40% on desktop, full width on mobile */}
            <div className="flex flex-1 flex-col justify-center items-center bg-primary px-6 py-12">
                <form
                    onSubmit={handleSubmit}
                    className="flex flex-col w-full max-w-[448px]"
                    noValidate
                >
                    {/* Heading */}
                    <h2 className="text-display-xs font-bold text-primary font-display">Sign in to Helix Engage</h2>
                    <p className="mt-1 text-sm text-tertiary">Global Hospital</p>

                    {/* Role is determined by platform — no selector needed */}

                    {/* Google sign-in */}
                    <div className="mt-6">
                        <SocialButton
                            social="google"
                            size="lg"
                            theme="gray"
                            type="button"
                            onClick={handleGoogleSignIn}
                            className="w-full rounded-xl py-3 border-2 border-secondary font-semibold hover:bg-secondary transition duration-300 ease-[cubic-bezier(0.4,0,0.2,1)]"
                        >
                            Sign in with Google
                        </SocialButton>
                    </div>

                    {/* Divider */}
                    <div className="mt-6 flex items-center gap-3">
                        <div className="flex-1 h-px bg-secondary" />
                        <span className="text-xs font-semibold text-quaternary tracking-wider uppercase">or continue with</span>
                        <div className="flex-1 h-px bg-secondary" />
                    </div>

                    {/* Email input */}
                    <div className="mt-6">
                        <Input
                            label="Email"
                            type="email"
                            placeholder="sanjay@globalhospital.com"
                            value={email}
                            onChange={(value) => setEmail(value)}
                            size="md"
                        />
                    </div>

                    {/* Password input */}
                    <div className="mt-4">
                        <Input
                            label="Password"
                            type="password"
                            placeholder="Enter your password"
                            value={password}
                            onChange={(value) => setPassword(value)}
                            size="md"
                        />
                    </div>

                    {/* Error message */}
                    {error && (
                        <div className="mt-4 rounded-lg bg-error-primary p-3 text-sm text-error-primary">
                            {error}
                        </div>
                    )}

                    {/* Sign in button */}
                    <div className="mt-6">
                        <Button
                            type="submit"
                            size="lg"
                            color="primary"
                            isLoading={isLoading}
                            className="w-full rounded-xl py-3 font-semibold active:scale-[0.98] transition duration-300 ease-[cubic-bezier(0.4,0,0.2,1)]"
                        >
                            Sign in
                        </Button>
                    </div>
                </form>
            </div>
        </div>
    );
};
