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 {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { CreateUserRequest, UpdateUserRequest } from "@/lib/features/users/usersSlice";
import { User } from "@/lib/features/auth/authSlice";
import { getAvatarUrl } from "@/lib/utils";
import { useState, useEffect } from "react";

interface UserDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    user?: User | null;
    onSubmit: (data: CreateUserRequest | UpdateUserRequest) => void;
    isLoading: boolean;
}

export function UserDialog({ open, onOpenChange, user, onSubmit, isLoading }: UserDialogProps) {
    const [username, setUsername] = useState("");
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [role, setRole] = useState("user");
    const [avatar, setAvatar] = useState<File | null>(null);
    const [avatarPreview, setAvatarPreview] = useState<string | null>(null);

    useEffect(() => {
        if (user) {
            setUsername(user.username);
            setEmail(user.email);
            setPassword("");
            setRole(user.roles?.[0]?.name || "user");
            setAvatar(null);
            setAvatarPreview(null);
        } else {
            setUsername("");
            setEmail("");
            setPassword("");
            setRole("user");
            setAvatar(null);
            setAvatarPreview(null);
        }
    }, [user, open]);

    const onAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0] || null;
        setAvatar(file);
        if (avatarPreview) URL.revokeObjectURL(avatarPreview);
        setAvatarPreview(file ? URL.createObjectURL(file) : null);
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        const roles = [role];

        if (user) {
            const updateData: UpdateUserRequest = {
                id: user.id,
                username,
                email,
                roles
            };
            if (password) updateData.password = password;
            if (avatar) updateData.avatar = avatar;
            onSubmit(updateData);
        } else {
            const createData: CreateUserRequest = {
                username,
                email,
                password,
                roles,
                avatar: avatar || undefined
            };
            onSubmit(createData);
        }
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-[425px]">
                <DialogHeader>
                    <DialogTitle>{user ? "Kullanıcıyı Düzenle" : "Yeni Kullanıcı Ekle"}</DialogTitle>
                    <DialogDescription>
                        {user ? "Kullanıcı bilgilerini güncelleyin." : "Yeni bir kullanıcı oluşturun."}
                    </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">
                                Username
                            </Label>
                            <Input
                                id="username"
                                value={username}
                                onChange={(e) => setUsername(e.target.value)}
                                className="col-span-3"
                                required
                            />
                        </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={email}
                                onChange={(e) => setEmail(e.target.value)}
                                className="col-span-3"
                                required
                            />
                        </div>
                        <div className="grid grid-cols-4 items-center gap-4">
                            <Label htmlFor="password" className="text-right">
                                Şifre
                            </Label>
                            <Input
                                id="password"
                                type="password"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                className="col-span-3"
                                placeholder={user ? "Değiştirmek için girin" : "Şifre"}
                                required={!user}
                            />
                        </div>
                        <div className="grid grid-cols-4 items-center gap-4">
                            <Label htmlFor="role" className="text-right">
                                Rol
                            </Label>
                            <Select onValueChange={setRole} value={role}>
                                <SelectTrigger className="w-[180px]">
                                    <SelectValue placeholder="Rol Seçin" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="user">User</SelectItem>
                                    <SelectItem value="admin">Admin</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                        <div className="grid grid-cols-4 items-center gap-4">
                            <Label htmlFor="avatar" className="text-right">
                                Avatar
                            </Label>
                            <div className="col-span-3 flex items-center gap-4">
                                <Avatar className="h-14 w-14">
                                    <AvatarImage
                                        src={avatarPreview ?? (user ? getAvatarUrl(user.avatar_url) : undefined)}
                                        alt={username || "Avatar"}
                                    />
                                    <AvatarFallback className="text-lg">
                                        {username?.slice(0, 2).toUpperCase() || "?"}
                                    </AvatarFallback>
                                </Avatar>
                                <Input
                                    id="avatar"
                                    type="file"
                                    accept="image/*"
                                    onChange={onAvatarChange}
                                    className="cursor-pointer"
                                />
                            </div>
                        </div>
                    </div>
                    <DialogFooter>
                        <Button type="submit" disabled={isLoading}>
                            {isLoading ? "Kaydediliyor..." : "Kaydet"}
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}
