"use client";

import { GRAVATAR_DEFAULT } from "@/lib/constants";
import { AliasEntry } from "@/lib/db";
import { isAdmin, sha256sum } from "@/lib/util";
import { Avatar, Badge, Button, Card, Code, Dialog, Flex, Grid, Heading, Table, Text } from "@radix-ui/themes";
import { useContext, useEffect, useState } from "react";
import GhostMessage from "../GhostMessage";
import { BananaIcon } from "lucide-react";
import LoadingSpinner from "../LoadingSpinner";
import { approveAlias, deleteAlias, fetchUserAliases } from "@/lib/actions";
import GenericConfirmationDialog from "../GenericConfirmationDialog";
import CreateAliasButton from "./CreateAliasButton";
import { ToastContext } from "@/lib/providers/ToastProvider";

export default function ManageUserButton({ email }: { email: string }) {
  const [aliases, setAliases] = useState<AliasEntry[] | null>(null);
  const toast = useContext(ToastContext);

  useEffect(() => {
    fetchUserAliases(email).then(setAliases);
  }, [email]);

  return (
    <Dialog.Root>
      <Dialog.Trigger>
        <Button variant="soft">Manage</Button>
      </Dialog.Trigger>
      <Dialog.Content>
        <Dialog.Title>
          Manage user
        </Dialog.Title>

        <Grid gap="4">
          <Card className="h-fit">
            <Flex direction="row" gap="3" align="center">
              <Avatar
                size="4"
                src={`https://gravatar.com/avatar/${sha256sum(email)}?d=${GRAVATAR_DEFAULT}`}
                fallback={email.slice(0, 1) || "@"}
              />
              <Flex direction="column">
                <Text>{email}</Text>
                <Text size="2" weight="light">{isAdmin(email) ? "Administrator" : "User"}</Text>
              </Flex>
            </Flex>
          </Card>

          <Card className="h-fit min-w-40">
            <Flex mb="4" justify="between">
              <Heading size="3">Aliases</Heading>
              <CreateAliasButton user={email} onCreate={(alias) => setAliases([...(aliases ?? []), alias])} />
            </Flex>

            {
              aliases
                ? aliases.length > 0
                  ? <Table.Root>
                    <Table.Header>
                      <Table.Row>
                        <Table.ColumnHeaderCell justify="start">Alias</Table.ColumnHeaderCell>
                        <Table.ColumnHeaderCell justify="end">Options</Table.ColumnHeaderCell>
                      </Table.Row>
                    </Table.Header>

                    <Table.Body>
                      {
                        aliases.map((alias) => (
                          <Table.Row key={alias.id}>
                            <Table.Cell justify="start">
                              {alias.alias}
                              {alias.pending && <Badge variant="soft" ml="3">Pending</Badge>}
                              {alias.temporary && <Badge variant="soft" ml="3" color="gray">Temporary</Badge>}
                            </Table.Cell>
                            <Table.Cell justify="end">
                              <Flex gap="3" justify="end">
                                {
                                  alias.pending &&
                                    <GenericConfirmationDialog
                                      title="Approve alias"
                                      description={<>Do you want to approve <Code>{alias.address}</Code>&apos;s alias request for <Code>{alias.alias}</Code>?</>}
                                      labelConfirm="Approve"
                                      action={async () => {
                                        try {
                                          await approveAlias(alias.alias);
                                          setAliases(aliases.map((a) => a.id == alias.id ? { ...alias, pending: false } : a));
                                          toast({
                                            title: "Alias approved",
                                            description: alias.alias,
                                            variant: "success",
                                          });
                                        } catch(e) {
                                          toast({
                                            title: "Failed to approve alias",
                                            description: `${e}`,
                                            variant: "error",
                                          });
                                        }
                                      }}
                                    >
                                      <Button size="1" variant="surface">Approve</Button>
                                    </GenericConfirmationDialog>
                                }
                                <GenericConfirmationDialog
                                  title="Delete alias"
                                  description={<>Are you sure you want to delete <Code>{alias.alias}</Code>?</>}
                                  labelConfirm="Delete"
                                  action={async () => {
                                    try {
                                      await deleteAlias(alias.alias);
                                      setAliases(aliases.filter((a) => a.id != alias.id));
                                      toast({
                                        title: "Alias deleted",
                                        description: alias.alias,
                                        variant: "success",
                                      });
                                    } catch(e) {
                                      toast({
                                        title: "Failed to delete alias",
                                        description: `${e}`,
                                        variant: "error",
                                      });
                                    }
                                  }}
                                >
                                  <Button size="1" variant="soft">Delete</Button>
                                </GenericConfirmationDialog>
                              </Flex>
                            </Table.Cell>
                          </Table.Row>
                        ))
                      }
                    </Table.Body>
                  </Table.Root>
                  : <GhostMessage icon={<BananaIcon />} header="No aliases" message="The user does not have any aliases" />
                : <GhostMessage icon={<LoadingSpinner />} header="Loading" />
            }
          </Card>
        </Grid>
      </Dialog.Content>
    </Dialog.Root>
  );
}
