"use client"

import React, { useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { registerSchema, RegisterInput } from '@/lib/auth-schema'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import Link from 'next/link'
import Swal from 'sweetalert2'
import { Turnstile } from 'nextjs-turnstile'
import { useRouter } from 'next/navigation'

const RegisterPage = () => {
    const [isLoading, setIsLoading] = useState(false)
    const [turnstileToken, setTurnstileToken] = useState<string | null>(null)
    const router = useRouter()
    const siteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITEKEY

    const {
        register,
        handleSubmit,
        formState: { errors },
    } = useForm<RegisterInput>({
        resolver: zodResolver(registerSchema),
    })

    const onSubmit = async (data: RegisterInput) => {
        if (siteKey && !turnstileToken) {
            Swal.fire({
                icon: 'warning',
                title: 'Güvenlik Doğrulaması',
                text: 'Lütfen robot olmadığınızı doğrulayın.',
            })
            return
        }

        setIsLoading(true)
        try {
            const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/auth/register`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: data.username,
                    email: data.email,
                    password: data.password
                }),
            })

            const result = await response.json()

            if (!response.ok) {
                throw new Error(result.error || result.message || 'Kayıt işlemi başarısız oldu.')
            }

            Swal.fire({
                title: 'Başarılı!',
                text: 'Kayıt işlemi başarıyla tamamlandı. Lütfen e-posta adresinizi doğrulayın.',
                icon: 'success',
                confirmButtonText: 'Giriş Yap',
            }).then(() => {
                router.push('/auth/login')
            })

        } catch (error: any) { // eslint-disable-line @typescript-eslint/no-explicit-any
            Swal.fire({
                title: 'Hata!',
                text: error.message || 'Bir sorun oluştu.',
                icon: 'error',
                confirmButtonText: 'Tamam',
            })
        } finally {
            setIsLoading(false)
        }
    }

    return (
        <div className="flex min-h-screen items-center justify-center bg-gray-100 p-4 dark:bg-gray-900">
            <Card className="w-full max-w-md shadow-xl">
                <CardHeader className="space-y-1">
                    <CardTitle className="text-2xl font-bold text-center">Kayıt Ol</CardTitle>
                    <CardDescription className="text-center">
                        Yeni bir hesap oluşturmak için bilgilerinizi girin
                    </CardDescription>
                </CardHeader>
                <CardContent>
                    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="username">Kullanıcı Adı</Label>
                            <Input
                                id="username"
                                placeholder="johndoe"
                                {...register('username')}
                                className={errors.username ? 'border-red-500' : ''}
                            />
                            {errors.username && (
                                <p className="text-sm text-red-500">{errors.username.message}</p>
                            )}
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="email">E-posta</Label>
                            <Input
                                id="email"
                                type="email"
                                placeholder="ornek@domain.com"
                                {...register('email')}
                                className={errors.email ? 'border-red-500' : ''}
                            />
                            {errors.email && (
                                <p className="text-sm text-red-500">{errors.email.message}</p>
                            )}
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="password">Şifre</Label>
                            <Input
                                id="password"
                                type="password"
                                placeholder="********"
                                {...register('password')}
                                className={errors.password ? 'border-red-500' : ''}
                            />
                            {errors.password && (
                                <p className="text-sm text-red-500">{errors.password.message}</p>
                            )}
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="confirmPassword">Şifre Tekrar</Label>
                            <Input
                                id="confirmPassword"
                                type="password"
                                placeholder="********"
                                {...register('confirmPassword')}
                                className={errors.confirmPassword ? 'border-red-500' : ''}
                            />
                            {errors.confirmPassword && (
                                <p className="text-sm text-red-500">{errors.confirmPassword.message}</p>
                            )}
                        </div>

                        {siteKey && (
                            <div className="flex justify-center my-4">
                                <Turnstile
                                    siteKey={siteKey}
                                    onSuccess={(token) => setTurnstileToken(token)}
                                    onError={() => setTurnstileToken(null)}
                                    onExpire={() => setTurnstileToken(null)}
                                />
                            </div>
                        )}

                        <Button type="submit" className="w-full" disabled={isLoading}>
                            {isLoading ? 'Kaydediliyor...' : 'Kayıt Ol'}
                        </Button>
                    </form>
                </CardContent>
                <CardFooter className="justify-center">
                    <p className="text-sm text-gray-500">
                        Zaten hesabınız var mı?{' '}
                        <Link href="/auth/login" className="text-blue-600 hover:underline">
                            Giriş Yap
                        </Link>
                    </p>
                </CardFooter>
            </Card>
        </div>
    )
}

export default RegisterPage
