'use client'

import { useState } from 'react'
import Link from 'next/link'
import { signIn } from 'next-auth/react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
import { AlertTriangle, Loader2 } from 'lucide-react'

export default function LoginPage() {
  const [error, setError] = useState<string | null>(null)
  const [pending, setPending] = useState(false)
  const [providerPending, setProviderPending] = useState<null | 'google' | 'github'>(null)

  async function onSubmit(formData: FormData) {
    setError(null)
    setPending(true)

    const email = String(formData.get('email') ?? '')
    const password = String(formData.get('password') ?? '')

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

    if (!result || result.error) {
      setError('Giriş başarısız')
      setPending(false)
      return
    }

    window.location.href = '/admin/users'
  }

  async function onProviderLogin(provider: 'google' | 'github') {
    setError(null)
    setProviderPending(provider)
    await signIn(provider, { callbackUrl: '/admin/users' })
  }

  return (
    <div className="flex min-h-[calc(100vh-4rem)] items-center justify-center px-4 py-12">
      <Card className="w-full max-w-sm">
        <CardHeader className="text-center">
          <CardTitle className="text-2xl">Hoş Geldiniz</CardTitle>
          <CardDescription>Hesabınıza giriş yapın</CardDescription>
        </CardHeader>

        <CardContent>
          <div className="mb-4 grid grid-cols-1 gap-2">
            <Button
              type="button"
              variant="outline"
              disabled={providerPending !== null}
              onClick={() => void onProviderLogin('google')}
            >
              {providerPending === 'google' && <Loader2 className="size-4 animate-spin" />}
              Google ile giris yap
            </Button>
            <Button
              type="button"
              variant="outline"
              disabled={providerPending !== null}
              onClick={() => void onProviderLogin('github')}
            >
              {providerPending === 'github' && <Loader2 className="size-4 animate-spin" />}
              GitHub ile giris yap
            </Button>
          </div>

          <div className="mb-4 flex items-center gap-3">
            <div className="h-px flex-1 bg-border" />
            <span className="text-xs text-muted-foreground">veya e-posta ile devam et</span>
            <div className="h-px flex-1 bg-border" />
          </div>

          <form action={onSubmit} className="space-y-4">
            {error && (
              <div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2.5 text-sm text-destructive">
                <AlertTriangle className="mt-0.5 size-4 shrink-0" />
                {error}
              </div>
            )}

            <div className="space-y-1.5">
              <Label htmlFor="email">E-posta</Label>
              <Input id="email" name="email" type="email" required autoComplete="email" placeholder="ornek@mail.com" />
            </div>

            <div className="space-y-1.5">
              <Label htmlFor="password">Şifre</Label>
              <Input id="password" name="password" type="password" required autoComplete="current-password" placeholder="••••••••" />
            </div>

            <Button type="submit" disabled={pending} className="w-full">
              {pending && <Loader2 className="size-4 animate-spin" />}
              {pending ? 'Giriş yapılıyor…' : 'Giriş Yap'}
            </Button>
          </form>
        </CardContent>

        <CardFooter className="justify-center text-sm text-muted-foreground">
          Hesabınız yok mu?&nbsp;
          <Link href="/auth/register" className="font-medium text-primary underline-offset-4 hover:underline">
            Kayıt Ol
          </Link>
        </CardFooter>
      </Card>
    </div>
  )
}
