'use client'
import React, { useEffect, useState } from 'react'
import { Label } from '../ui/label'
import { Input } from '../ui/input'
import Link from 'next/link'
import { Button } from '../ui/button'
import { getProviders, signIn } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import { Separator } from '../ui/separator' 
import KeyIcon from '../icons/KeyIcon'
import OpenIDIcon from '../icons/OpenIDIcon'

interface Provider {
  id: string
  name: string
}

export default function LoginForm() {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('')
    const [error, setError] = useState('');
    const [providers, setProviders] = useState<Provider[]>([])
    const router = useRouter();

    useEffect(() => {
        // Fetch available auth providers
        const fetchProviders = async () => {
            const authProviders = await getProviders()
            if (authProviders) {
                // Filter out credentials provider (email/password)
                const filtered = Object.values(authProviders).filter(
                    p => p.id !== 'credentials'
                )
                setProviders(filtered)
            }
        }
        fetchProviders()
    }, [])

    async function handleSubmit(e: React.FormEvent) {
        e.preventDefault();

        const result = await signIn('credentials', {
            redirect: false,
            email,
            password,
        })

        console.log('[CLIENT] signIn result:', result)

        if (result?.error) {
            setError(result.error)
        } else {
            router.push('/dashboard')
        }
    }

    const handleOidcLogin = (providerId: string) => {
        signIn(providerId, { callbackUrl: '/dashboard' })
    }

    return (
        <div className="space-y-6">
            {/* OIDC Providers Section
            {providers.length > 0 && (
                <>
                    <div className="space-y-3">
                        <h3 className="text-center text-sm font-medium text-muted-foreground">
                            Sign in with
                        </h3>
                        <div className="grid grid-cols-1 gap-3">
                            {providers.map((provider) => (
                                <Button
                                    key={provider.id}
                                    type="button"
                                    variant="outline"
                                    className="w-full"
                                    onClick={() => handleOidcLogin(provider.id)}
                                >
                                    <span className="flex items-center justify-center gap-2">
                                        <OpenIDIcon />
                                        {provider.name}
                                    </span>
                                </Button>
                            ))}
                        </div>
                    </div>
                    <Separator className="my-6" />
                    <div className="text-center text-sm text-muted-foreground">
                        Or continue with email
                    </div>
                </>
            )} */}

            {/* Email/Password Form */}
            <form onSubmit={handleSubmit}>
                <div className='flex flex-col gap-6'>
                    <div className='grid gap-3'>
                        <Label htmlFor='email'>Email</Label>
                        <Input
                            id='email'
                            type='email'
                            placeholder='m@example.com'
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            required
                        />
                    </div>
                    <div className='grid gap-3'>
                        <div className='flex items-center'>
                            <Label htmlFor='password'>Password</Label>
                            <Link 
                                href={'#'}
                                className='ml-auto inline-block text-sm underline-offset-4 hover:underline'
                            >
                                Forgot your password?
                            </Link>
                        </div>
                        <Input 
                            id='password' 
                            type='password' 
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            required 
                        />
                    </div>
                    <div className='flex flex-col gap-3'>
                        <Button 
                            type="submit" 
                            className="w-full bg-brand-primary-600 hover:bg-brand-primary-400"
                        >
                            Sign in with Email
                        </Button>
                        {error && <p className="text-red-500 text-center">{error}</p>}
                    </div>
                </div>
            </form>
        </div>
    )
}
