import useHasPermission from '@/hooks/use-has-permission';
import { cancelInvitation } from '@/service/house.api';
import { INVITE_STATUS } from '@/types/enum';
import { authClient } from '@lib/auth-client';
import { m } from '@paraglide/messages';
import { useMutation } from '@tanstack/react-query';
import { Item, ItemContent, ItemDescription, ItemTitle } from '@ui/item';
import { Skeleton } from '@ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@ui/table';
import { toast } from 'sonner';
import RoleBadge from '../avatar/role-badge';
import { Button } from '../ui/button';

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

const CurrentUserInvitationList = ({ activeHouse }: InvitationListProps) => {
  const { refetch } = authClient.useActiveOrganization();
  const { hasPermission, isLoading } = useHasPermission(
    'invitation',
    'cancel',
    true,
  );

  const { mutate: cancelInvitationMutation } = useMutation({
    mutationFn: cancelInvitation,
    onSuccess: () => {
      refetch();
      toast.success(m.houses_page_message_cancel_invitation_success(), {
        richColors: true,
      });
    },
    onError: (error: ReturnError) => {
      console.error(error);
      const code = error.code as Parameters<
        typeof m.backend_message
      >[0]['code'];
      toast.error(m.backend_message({ code }), {
        richColors: true,
      });
    },
  });

  const handleCancelInvitation = (id: string) => {
    cancelInvitationMutation({ data: { id } });
  };

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

  return (
    <div className="overflow-hidden rounded-md border col-span-1 lg:col-span-3 shadow-xs bg-linear-to-br from-primary/5 to-card">
      <Table className="bg-white">
        <TableHeader>
          <TableRow>
            <TableHead className="px-4 bg-primary text-white text-sm w-1/2">
              {m.houses_page_ui_view_table_header_invite()}
            </TableHead>
            <TableHead className="px-4 bg-primary text-white text-sm w-1/2"></TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {activeHouse.invitations.length > 0 ? (
            activeHouse.invitations.map((item) => (
              <TableRow key={item.id}>
                <TableCell>
                  <Item>
                    <ItemContent>
                      <ItemTitle>
                        <strong>{m.houses_user_page_invite_label_to()}:</strong>{' '}
                        {item.email} - <RoleBadge type={item.role} />
                      </ItemTitle>
                      <ItemDescription>
                        <strong>
                          {m.houses_user_page_invite_label_status()}:{' '}
                          {m.invite_status({
                            status: item.status as INVITE_STATUS,
                          })}
                        </strong>
                      </ItemDescription>
                    </ItemContent>
                  </Item>
                </TableCell>
                <TableCell className="p-6">
                  <div className="flex justify-end gap-2">
                    {item.status === INVITE_STATUS.PENDING && hasPermission && (
                      <Button
                        variant="outline"
                        className="cursor-pointer w-20 py-4"
                        onClick={() => handleCancelInvitation(item.id)}
                      >
                        {m.ui_cancel_btn()}
                      </Button>
                    )}
                  </div>
                </TableCell>
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={2} className="h-24 text-center">
                No results.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  );
};

export default CurrentUserInvitationList;
