"use client";

import { fetchAllUsers } from "@/lib/actions";
import GhostMessage from "@/lib/components/ui/GhostMessage";
import LoadingSpinner from "@/lib/components/ui/LoadingSpinner";
import CreateUserButton from "@/lib/components/ui/admin/CreateUserButton";
import ManageUserButton from "@/lib/components/ui/admin/ManageUserButton";
import { GRAVATAR_DEFAULT } from "@/lib/constants";
import { isAdmin, sha256sum } from "@/lib/util";
import { Avatar, Badge, Button, Card, Flex, Heading, Table, Text, TextField } from "@radix-ui/themes";
import { SearchIcon, UserRoundXIcon } from "lucide-react";
import { useEffect, useMemo, useState } from "react";

export default function Users() {
  const [data, setData] = useState<string[] | null>(null);
  const [filter, setFilter] = useState("");
  const filtered = useMemo(() => filter.length ? data?.filter((email) => email.includes(filter)) : data, [data, filter]);

  useEffect(() => {
    fetchAllUsers().then(setData);
  }, []);

  return (
    <>
      <Flex pb="4" justify="between">
        <Heading>Users</Heading>
        <Flex gap="3" ml="3">
          <TextField.Root>
            <TextField.Slot>
              <SearchIcon size="16" />
            </TextField.Slot>
            <TextField.Input
              value={filter}
              onChange={(e) => setFilter(e.currentTarget.value)}
              placeholder="Filter table..."
            />
          </TextField.Root>
          <CreateUserButton onCreate={(user) => setData([...(data ?? []), user])} />
        </Flex>
      </Flex>

      <Card>
        {
          filtered
            ? filtered.length
              ? <Flex direction='column' className="flex-1">
                <Table.Root className="w-full">
                  <Table.Header>
                    <Table.Row>
                      <Table.ColumnHeaderCell justify='start'>Email</Table.ColumnHeaderCell>
                      <Table.ColumnHeaderCell justify='end'>Actions</Table.ColumnHeaderCell>
                    </Table.Row>
                  </Table.Header>

                  <Table.Body>
                    {filtered.map((email) => (
                      <Table.Row key={email}>
                        <Table.Cell justify='start'>
                          <Flex direction='row' gap='4' align='center'>
                            <Avatar
                              size="2"
                              src={`https://gravatar.com/avatar/${sha256sum(email)}?d=${GRAVATAR_DEFAULT}`}
                              radius='full'
                              fallback={email.slice(0, 1) || "@"}
                            />
                            <Text size='2'>{email}</Text>
                            {isAdmin(email) && <Badge variant="surface">Admin</Badge>}
                          </Flex>
                        </Table.Cell>
                        <Table.Cell justify='end'>
                          <ManageUserButton email={email} />
                        </Table.Cell>
                      </Table.Row>
                    ))}
                  </Table.Body>
                </Table.Root>
              </Flex>
              : <GhostMessage icon={<UserRoundXIcon />} header="No users" message="Try adjusting your search query" />
            : <GhostMessage icon={<LoadingSpinner />} header="Loading" />
        }
      </Card>
    </>
  );
}