"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select"
import { Card, CardContent } from "@/components/ui/card"
import { toast } from "sonner"
import { Loader2 } from "lucide-react"
import { createUser, updateUser } from "@/app/(dashboard)/dashboard/users/actions"

const userSchema = z.object({
    firstName: z.string().min(2, "Ad en az 2 karakter olmalıdır."),
    lastName: z.string().min(2, "Soyad en az 2 karakter olmalıdır."),
    email: z.string().email("Geçerli bir e-posta adresi giriniz."),
    password: z.string().optional(), // Password is optional on edit
    role: z.enum(["admin", "user"]),
}).refine((data) => {
    // If we are creating a NEW user (no ID passed in props effectively, but schema doesn't know props),
    // we generally want password required. But here we'll handle it in the component logic or strictly separate schemas.
    // For simplicity, we make password optional in Zod but check it in onSubmit if it's a create action.
    return true
})

type UserFormValues = z.infer<typeof userSchema>

interface UserFormProps {
    initialData?: {
        id: string
        firstName: string
        lastName: string
        email: string
        role: "admin" | "user"
    }
}

export function UserForm({ initialData }: UserFormProps) {
    const router = useRouter()
    const [loading, setLoading] = useState(false)

    const form = useForm<UserFormValues>({
        resolver: zodResolver(userSchema),
        defaultValues: initialData ? {
            firstName: initialData.firstName,
            lastName: initialData.lastName,
            email: initialData.email,
            password: "", // Empty password means no change
            role: initialData.role,
        } : {
            firstName: "",
            lastName: "",
            email: "",
            password: "",
            role: "user",
        },
    })

    const onSubmit = async (data: UserFormValues) => {
        setLoading(true)
        try {
            let result;
            if (initialData) {
                // Update
                result = await updateUser(initialData.id, data)
            } else {
                // Create
                if (!data.password || data.password.length < 6) {
                    toast.error("Yeni kullanıcı için şifre gereklidir (min 6 karakter).")
                    setLoading(false)
                    return
                }
                result = await createUser(data.firstName, data.lastName, data.email, data.password, data.role)
            }

            if (result.error) {
                toast.error(result.error)
                return
            }

            toast.success(initialData ? "Kullanıcı güncellendi." : "Kullanıcı oluşturuldu.")
            router.push("/dashboard/users")
            router.refresh()
        } catch (error) {
            toast.error("Bir sorun oluştu.")
        } finally {
            setLoading(false)
        }
    }

    return (
        <Card className="max-w-xl">
            <CardContent className="pt-6">
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                        <div className="grid grid-cols-2 gap-4">
                            <FormField
                                control={form.control}
                                name="firstName"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Ad</FormLabel>
                                        <FormControl>
                                            <Input placeholder="Ahmet" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="lastName"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Soyad</FormLabel>
                                        <FormControl>
                                            <Input placeholder="Yılmaz" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </div>

                        <FormField
                            control={form.control}
                            name="email"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>E-posta</FormLabel>
                                    <FormControl>
                                        <Input placeholder="ahmet@parakasa.com" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="password"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Şifre</FormLabel>
                                    <FormControl>
                                        <Input type="password" placeholder={initialData ? "Değiştirmek için yeni şifre girin" : "******"} {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="role"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Rol</FormLabel>
                                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                                        <FormControl>
                                            <SelectTrigger>
                                                <SelectValue placeholder="Rol seçin" />
                                            </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                            <SelectItem value="user">Kullanıcı</SelectItem>
                                            <SelectItem value="admin">Yönetici</SelectItem>
                                        </SelectContent>
                                    </Select>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <Button type="submit" disabled={loading} className="w-full">
                            {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                            Kullanıcı Oluştur
                        </Button>
                    </form>
                </Form>
            </CardContent>
        </Card>
    )
}
