import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Skeleton } from "@/components/ui/skeleton";

import apiInstance from "@/services/api";
import { logout } from "@/services/auth";

interface UserProfile {
    username: string;
    email: string;
    profile: {
        show_mature: boolean;
    };
}

const UserDropdown = () => {
    const [user, setUser] = useState<UserProfile | null>(null);
    const [loading, setLoading] = useState(true);
    const [nsfwEnabled, setNsfwEnabled] = useState(false);

    useEffect(() => {
        const fetchUser = async () => {
            try {
                const response = await apiInstance.get<UserProfile>("user/profile/");
                setUser(response.data);
                setNsfwEnabled(response.data.profile.show_mature);
            } catch (error) {
                console.error("Failed to fetch user:", error);
            } finally {
                setLoading(false);
            }
        };
        fetchUser();
    }, []);

    const handleNsfwToggle = async () => {
        if (!user) return;
        const newSetting = !nsfwEnabled;
        setNsfwEnabled(newSetting);

        try {
            await apiInstance.patch("user/profile/", {
                profile: { show_mature: newSetting },
            });
        } catch (error) {
            console.error("Failed to update NSFW setting:", error);
            setNsfwEnabled(!newSetting);
        }
    };

    const handleLogout = () => {
        logout();
    };

    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <Link className="relative flex items-center space-x-2">
                    {loading ? (
                        <Skeleton className="h-8 w-8 rounded-full bg-gray-500 hover:bg-gray-600" />
                    ) : (
                        <div className="h-8 w-8 bg-gray-500 hover:bg-gray-600 rounded-full flex items-center justify-center shadow-lg">
                            {user?.username.charAt(0).toUpperCase()}
                        </div>
                    )}
                </Link>
            </DropdownMenuTrigger>

            <DropdownMenuContent align="end" className="p-4 shadow-lg rounded-lg border">
                {loading ? (
                    <div className="flex flex-col space-y-3">
                        <Skeleton className="h-4 w-32" />
                        <Skeleton className="h-4 w-48" />
                        <Skeleton className="h-10 w-full" />
                    </div>
                ) : (
                    <div className="space-y-2">
                        {/* User Info */}
                        <div className="text-sm">
                            <p className="font-semibold">{user?.username}</p>
                            <p className="text-gray-500">{user?.email}</p>
                        </div>

                        <div className="border-t my-2"></div>

                        {/* NSFW Toggle (Prevent Dropdown from Closing) */}
                        <DropdownMenuItem asChild>
                            <div
                                className="flex items-center justify-between w-full cursor-pointer"
                                onClick={(e) => e.stopPropagation()} // Prevents dropdown from closing
                            >
                                <span className="text-sm">Show NSFW Content</span>
                                <Switch checked={nsfwEnabled} onCheckedChange={handleNsfwToggle} />
                            </div>
                        </DropdownMenuItem>

                        {/* Logout Button */}
                        <Button variant="destructive" className="w-full" onClick={handleLogout}>
                            Logout
                        </Button>
                    </div>
                )}
            </DropdownMenuContent>
        </DropdownMenu>
    );
};

export default UserDropdown;

