import { authClient } from '@lib/auth-client';
import { m } from '@paraglide/messages';
import { Item, ItemContent, ItemDescription, ItemTitle } from '@ui/item';
import { Skeleton } from '@ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@ui/table';
import { useAuth } from '../auth/auth-provider';
import RoleBadge from '../avatar/role-badge';
import InviteUserAction from './invite-user-dialog';
import RemoveUserFormHouse from './remove-user-form-house';

type CurrentUserMemberListProps = {
  activeHouse: ReturnType<typeof authClient.useActiveOrganization>['data'];
};

const CurrentUserMemberList = ({ activeHouse }: CurrentUserMemberListProps) => {
  const { session } = useAuth();

  if (!activeHouse) {
    return <Skeleton className="col-span-1 lg:col-span-2 h-80 rounded-xl" />;
  }

  return (
    <div className="overflow-hidden rounded-md border col-span-1 lg:col-span-2 shadow-xs bg-linear-to-br from-primary/5 to-card">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead className="px-4 bg-primary text-white text-sm w-1/3">
              {m.houses_page_ui_table_header_name()} &{' '}
              {m.houses_page_ui_view_table_header_email()}
            </TableHead>
            <TableHead className="px-4 bg-primary text-white text-sm w-1/3">
              {m.houses_page_ui_view_table_header_role()}
            </TableHead>
            <TableHead className="px-4 bg-primary">
              <div className="flex justify-end gap-2">
                <InviteUserAction />
              </div>
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {activeHouse.members.map((member) => (
            <TableRow key={member.user.id}>
              <TableCell className="px-4">
                <Item className="p-0">
                  <ItemContent>
                    <ItemTitle>{member.user.name}</ItemTitle>
                    <ItemDescription>{member.user.email}</ItemDescription>
                  </ItemContent>
                </Item>
              </TableCell>
              <TableCell className="px-4">
                <RoleBadge type={member.role} />
              </TableCell>
              <TableCell className="px-4">
                <div className="flex justify-end gap-2">
                  {member.role !== 'owner' &&
                    session.user.id !== member.user.id && (
                      <RemoveUserFormHouse member={member} />
                    )}
                </div>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
};

export default CurrentUserMemberList;
