import { ChevronDown, Hash, Volume2 } from "lucide-react";
import React from "react";
import { NavLink } from "react-router";
import { useShallow } from "zustand/react/shallow";
import { useFetchUsers } from "~/hooks/use-fetch-user";
import { deleteChannel } from "~/lib/api/client/server";
import { ChannelType, type ServerChannel } from "~/lib/api/types";
import { cn } from "~/lib/utils";
import { useChannelsVoiceStateStore } from "~/stores/channels-voice-state";
import { useGatewayStore } from "~/stores/gateway-store";
import { useUsersStore } from "~/stores/users-store";
import { useVoiceStateStore } from "~/stores/voice-state-store";
import { Button } from "../ui/button";
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from "../ui/context-menu";
import UserAvatar from "../user-avatar";
import UserContextMenu from "../user-context-menu";

interface ChannelListItemProps {
    channel: ServerChannel;
}

const onDeleteChannel = async (channel: ServerChannel) => {
    await deleteChannel(channel.serverId, channel.id);
};

interface ChannelItemWrapperProps {
    channel: ServerChannel;
    icon: React.ReactNode;
    onButtonClick?: () => void; // For direct button clicks (e.g., join voice)
    navTo?: string; // If provided, the button becomes a NavLink
    isExplicitlyActive?: boolean; // To set active state externally (e.g., current voice channel)
}

function ChannelItemWrapper({ channel, icon, onButtonClick, navTo, isExplicitlyActive }: ChannelItemWrapperProps) {
    const buttonInnerContent = (
        <div className="flex items-center gap-2 max-w-72">
            <div>{icon}</div>
            <div className="truncate">{channel.name}</div>
        </div>
    );

    const renderButton = (isNavLinkActive?: boolean) => {
        // Active state priority: explicit prop > NavLink state > default (false)
        const isActive = isExplicitlyActive ?? isNavLinkActive ?? false;
        return (
            <Button
                variant="secondary"
                size="sm"
                className={cn(
                    "justify-start w-full shadow-sm",
                    isActive ? "bg-accent hover:bg-accent" : "bg-secondary",
                )}
                onClick={!navTo ? onButtonClick : undefined}
            >
                {buttonInnerContent}
            </Button>
        );
    };

    let triggerContent: React.ReactNode;
    if (navTo) {
        triggerContent = (
            <NavLink to={navTo} discover="none">
                {({ isActive: navLinkIsActive }) => renderButton(navLinkIsActive)}
            </NavLink>
        );
    } else {
        // For non-NavLink cases (like voice channel), active state is determined by isExplicitlyActive
        triggerContent = renderButton();
    }

    return (
        <ContextMenu>
            <ContextMenuTrigger asChild>{triggerContent}</ContextMenuTrigger>
            <ContextMenuContent>
                <ContextMenuItem variant="destructive" onClick={() => onDeleteChannel(channel)}>
                    Delete
                </ContextMenuItem>
            </ContextMenuContent>
        </ContextMenu>
    );
}

function ServerCategory({ channel }: ChannelListItemProps) {
    return (
        <div className="text-xs flex flex-row justify-between mt-4">
            <div className="grow">
                <div className="flex items-center gap-1">
                    {channel.name}
                    <ChevronDown className="size-4" />
                </div>
            </div>
        </div>
    );
}

function ServerVoice({ channel }: ChannelListItemProps) {
    const updateVoiceState = useGatewayStore((state) => state.updateVoiceState);
    const voiceStateChannel = useVoiceStateStore((state) => state.activeChannel);
    const channelVoiceState = useChannelsVoiceStateStore((state) => state.channels[channel.id]) || {};
    const userIds = Object.keys(channelVoiceState.users ?? {});
    useFetchUsers(userIds);

    const users = useUsersStore(useShallow((state) => state.users));

    const channelUsers = React.useMemo(() => userIds.map((userId) => users[userId]).filter(Boolean), [userIds, users]);

    const isCurrentVoiceChannel =
        voiceStateChannel?.serverId === channel.serverId && voiceStateChannel.channelId === channel.id;

    const handleJoinVoiceChannel = () => {
        if (isCurrentVoiceChannel) return;
        updateVoiceState(channel.serverId, channel.id);
    };

    return (
        <>
            <ChannelItemWrapper
                channel={channel}
                icon={<Volume2 />}
                onButtonClick={handleJoinVoiceChannel}
                isExplicitlyActive={isCurrentVoiceChannel}
            />
            {channelUsers.length > 0 && (
                <div className="ml-2 border-l-2 flex flex-col gap-1 pl-4 py-1">
                    {" "}
                    {/* Added py-1 for spacing */}
                    {channelUsers.map((user) => (
                        <React.Fragment key={user.id}>
                            <UserContextMenu userId={user.id}>
                                <div className="flex items-center gap-2 max-w-72 p-1 hover:bg-secondary/80 rounded">
                                    {" "}
                                    {/* Added padding and hover for better UX */}
                                    <UserAvatar user={user} className="size-6" />
                                    {user.displayName || user.username}
                                </div>
                            </UserContextMenu>
                        </React.Fragment>
                    ))}
                </div>
            )}
        </>
    );
}

function ServerText({ channel }: ChannelListItemProps) {
    return (
        <ChannelItemWrapper channel={channel} icon={<Hash />} navTo={`/app/server/${channel.serverId}/${channel.id}`} />
    );
}

export default function ServerChannelListItem({ channel }: ChannelListItemProps) {
    switch (channel.type) {
        case ChannelType.SERVER_CATEGORY:
            return <ServerCategory channel={channel} />;
        case ChannelType.SERVER_VOICE:
            return <ServerVoice channel={channel} />;
        case ChannelType.SERVER_TEXT:
            return <ServerText channel={channel} />;
        default:
            return null;
    }
}
