import { authClient } from '@lib/auth-client';
import { cn } from '@lib/utils';
import { m } from '@paraglide/messages';
import { CheckIcon, WarehouseIcon } from '@phosphor-icons/react';
import { housesQueries } from '@service/queries';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@ui/card';
import parse from 'html-react-parser';
import { toast } from 'sonner';
import {
  Item,
  ItemActions,
  ItemContent,
  ItemDescription,
  ItemTitle,
} from '../ui/item';
import { ScrollArea, ScrollBar } from '../ui/scroll-area';
import { Skeleton } from '../ui/skeleton';
import CreateNewHouse from './create-house-dialog';

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

const CurrentUserHouseList = ({ activeHouse }: CurrentUserHouseListProps) => {
  const { data: houses } = useQuery(housesQueries.currentUser());

  const activeHouseAction = async ({
    id,
    slug,
  }: {
    id: string;
    slug: string;
  }) => {
    const { data, error } = await authClient.organization.setActive({
      organizationId: id,
      organizationSlug: slug,
    });

    if (error) {
      toast.error(error.message, { richColors: true });
    }

    if (data) {
      toast.success(
        parse(
          m.houses_user_page_message_active_house_success({ house: data.name }),
        ),
        {
          richColors: true,
        },
      );
    }
  };

  if (!activeHouse || !houses) {
    return <Skeleton className="col-span-2 h-80 w-full rounded-xl" />;
  }

  return (
    <Card className="col-span-1 lg:col-span-3">
      <CardHeader>
        <CardTitle className="text-xl flex items-center gap-2">
          <WarehouseIcon size={24} />
          {m.houses_page_ui_title()}
          <CreateNewHouse isPersonal className="ml-auto" />
        </CardTitle>
      </CardHeader>
      <CardContent>
        <ScrollArea className="w-full rounded-md border whitespace-nowrap bg-gray-50">
          <div className="flex w-max p-4 space-x-4">
            {houses.map((house) => {
              const isActive = house.id === activeHouse.id;

              return (
                <Item
                  variant="outline"
                  className={cn('w-100 bg-white', {
                    'bg-linear-to-tr from-white/2 to-green-200': isActive,
                  })}
                  key={house.id}
                >
                  <ItemContent>
                    <ItemTitle
                      className="font-bold text-sm text-(--house-color)"
                      style={
                        { '--house-color': house.color } as React.CSSProperties
                      }
                    >
                      {house.name}
                    </ItemTitle>
                    <ItemDescription>
                      <strong>{m.houses_page_ui_table_header_members()}</strong>
                      :&nbsp;
                      {house._count.members}
                    </ItemDescription>
                  </ItemContent>
                  <ItemActions>
                    <Button
                      variant="outline"
                      data-active={isActive}
                      disabled={isActive}
                      className={cn('rounded-full cursor-pointer', {
                        'disabled:bg-green-500! disabled:border-green-500!':
                          isActive,
                        'bg-amber-50! text-amber-600! border-amber-600!':
                          !isActive,
                      })}
                      size="icon-lg"
                      onClick={() =>
                        activeHouseAction({ id: house.id, slug: house.slug })
                      }
                    >
                      <CheckIcon weight="bold" />
                      <span className="sr-only">
                        {m.houses_page_house_active_btn()}
                      </span>
                    </Button>
                  </ItemActions>
                </Item>
              );
            })}
          </div>
          <ScrollBar orientation="horizontal" />
        </ScrollArea>
      </CardContent>
    </Card>
  );
};

export default CurrentUserHouseList;
