"use client"

import { Button } from "@/components/ui/button"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { User, UserPayload } from "@/types/user"
import { useState } from "react"
import { userService } from "@/services/userService"
import { useSession } from "next-auth/react"
import { toast } from "sonner"
import { useRouter } from "next/navigation"

interface UserDialogProps {
    open: boolean
    onOpenChange: (open: boolean) => void
    user: User
    onSuccess?: () => void
}

export function UserDialog({ open, onOpenChange, user, onSuccess }: UserDialogProps) {
    const { data: session } = useSession()
    const router = useRouter()
    const [loading, setLoading] = useState(false)
    const [formData, setFormData] = useState<UserPayload>({
        username: user.username,
        email: user.email,
        is_admin: user.is_admin,
        password: "",
    })

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault()
        if (!session?.user?.accessToken) return

        setLoading(true)
        try {
            // Create a payload copy to manipulate
            const payload = { ...formData }
            // Remove password if it's empty so we don't overwrite with empty string
            if (!payload.password || payload.password.trim() === "") {
                delete payload.password
            }

            await userService.updateUser(session.user.accessToken, user.id, payload)
            toast.success("Kullanıcı güncellendi")
            onOpenChange(false)
            if (onSuccess) onSuccess() // Trigger parent refresh
            router.refresh()
        } catch (error) {
            toast.error("Kullanıcı güncellenirken bir hata oluştu")
            console.error(error)
        } finally {
            setLoading(false)
        }
    }

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-[425px]">
                <DialogHeader>
                    <DialogTitle>Kullanıcı Düzenle</DialogTitle>
                    <DialogDescription>
                        Kullanıcı bilgilerini buradan güncelleyebilirsiniz. Şifre alanını boş bırakırsanız değişmez.
                    </DialogDescription>
                </DialogHeader>
                <form onSubmit={handleSubmit}>
                    <div className="grid gap-4 py-4">
                        <div className="grid grid-cols-4 items-center gap-4">
                            <Label htmlFor="username" className="text-right">
                                Kullanıcı Adı
                            </Label>
                            <Input
                                id="username"
                                value={formData.username}
                                onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                                className="col-span-3"
                            />
                        </div>
                        <div className="grid grid-cols-4 items-center gap-4">
                            <Label htmlFor="email" className="text-right">
                                Email
                            </Label>
                            <Input
                                id="email"
                                type="email"
                                value={formData.email}
                                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                className="col-span-3"
                            />
                        </div>
                        <div className="grid grid-cols-4 items-center gap-4">
                            <Label htmlFor="password" className="text-right">
                                Yeni Şifre
                            </Label>
                            <Input
                                id="password"
                                type="password"
                                placeholder="Değişmeyecekse boş bırakın"
                                value={formData.password || ""}
                                onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                                className="col-span-3"
                            />
                        </div>
                        {/* Admin role toggle could be added here if needed */}
                    </div>
                    <DialogFooter>
                        <Button type="submit" disabled={loading}>
                            {loading ? "Kaydediliyor..." : "Kaydet"}
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    )
}
