import { Check } from "lucide-react";
import { NavLink } from "react-router";
import { useShallow } from "zustand/react/shallow";
import { useFetchUsers } from "~/hooks/use-fetch-user";
import type { RecipientChannel } from "~/lib/api/types";
import { cn } from "~/lib/utils";
import { useUsersStore } from "~/stores/users-store";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import UserAvatar from "../user-avatar";
import { OnlineStatus } from "./online-status";

interface PrivateChannelListItemProps {
    channel: RecipientChannel;
}

export default function PrivateChannelListItem({ channel }: PrivateChannelListItemProps) {
    const currentUserId = useUsersStore((state) => state.currentUserId);

    const recipients = channel.recipients.filter((recipient) => recipient !== currentUserId);

    useFetchUsers(recipients);

    const recipientsUsers = useUsersStore(
        useShallow((state) => recipients.map((recipient) => state.users[recipient]).filter(Boolean)),
    );

    const renderSystemBadge = recipientsUsers.some((recipient) => recipient.system) && recipients.length === 1;

    return (
        <>
            <NavLink to={`/app/@me/channels/${channel.id}`}>
                {({ isActive }) => (
                    <Button
                        variant="secondary"
                        size="none"
                        asChild
                        className={cn(
                            "w-full flex flex-row justify-start shadow-sm",
                            isActive ? "bg-accent hover:bg-accent" : "",
                        )}
                    >
                        <div className="flex items-center gap-2 max-w-72 p-2">
                            <div>
                                <OnlineStatus status="online">
                                    <UserAvatar
                                        user={recipientsUsers.find((recipient) => recipient.id !== currentUserId)}
                                    />
                                </OnlineStatus>
                            </div>
                            <div className="truncate">
                                {recipientsUsers
                                    .map((recipient) => recipient.displayName || recipient.username)
                                    .join(", ")}
                            </div>
                            {renderSystemBadge && (
                                <Badge variant="default">
                                    {" "}
                                    <Check /> System
                                </Badge>
                            )}
                        </div>
                    </Button>
                )}
            </NavLink>
        </>
    );
}
