import Avatar from "@/components/avatar";
import { Input } from "@/components/ui/input";
import { useExpenseStore } from "@/lib/store/expense-store";
import React from "react";
import FriendSelect from "../friend/friend-select";
import { api } from "@/trpc/react";
import { Button } from "@/components/ui/button";
import { XIcon } from "lucide-react";
import type { User } from "@/server/db/schema";

export const UserBadge = ({
  user,
  children,
}: {
  user: User;
  children?: React.ReactNode;
}) => {
  return (
    <div className="border rounded-full gap-1 flex items-center w-max pr-1">
      <Avatar src={user.image} fb={user.name} className="size-6" />
      <span className="text-sm">{user.name}</span>

      {children}
    </div>
  );
};

export default function ExpenseParticipants({
  sessionUserId,
}: {
  sessionUserId: string;
}) {
  const [friends] = api.friend.getAll.useSuspenseQuery();
  const participants = useExpenseStore((state) => state.participants);
  const addParticipant = useExpenseStore((state) => state.addParticipant);
  const removeParticipant = useExpenseStore((state) => state.removeParticipant);
  const excludeIds = participants.map((user) => user.id!);

  return (
    <div className="p-4 space-y-4">
      <div className=" flex gap-2 w-full items-center flex-wrap">
        <h5 className="w-18">You and</h5>

        <FriendSelect
          excludeIds={excludeIds}
          onSelect={(userId) => {
            addParticipant(
              friends.find((friend) => friend.user.id === userId)!.user
            );
          }}
        />

        {participants.map((user) => (
          <ul key={user.id}>
            <UserBadge user={user}>
              {sessionUserId !== user.id && (
                <Button
                  className=" rounded-full aspect-square size-6"
                  variant="destructive"
                  onClick={(e) => {
                    e.preventDefault();
                    removeParticipant(user.id!);
                  }}
                >
                  <XIcon className="size-4" />
                </Button>
              )}
            </UserBadge>
          </ul>
        ))}
      </div>
    </div>
  );
}
