import { Check } from "lucide-react"
import { NavLink } from "react-router"
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.id !== currentUserId);
    const renderSystemBadge = recipients.some(recipient => recipient.system) && recipients.length === 1

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