import React from "react";
import { useUserContext } from "./UserContext";
import {
  Avatar,
  Box,
  Button,
  Flex,
  Modal,
  Paper,
  TextInput,
  Title,
} from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { NavigateButton } from "./NavigateButton";
import { Link } from "react-router";

export const AuthorizeMastodonModal: React.FC<{
  opened: boolean;
  onClose: () => void;
}> = ({ opened, onClose }) => {
  const [serverName, setServerName] = React.useState("rubber.social");
  const [loading, setLoading] = React.useState(false);

  const handleClick = React.useCallback(() => {
    setLoading(true);
    fetch(`/api/mastodon_oauth?server=${encodeURI(serverName)}`)
      .then((response) => response.json())
      .then((json) => {
        if (json["url"]) {
          window.location.href = json["url"];
        }
      });
  }, []);

  return (
    <Modal opened={opened} onClose={onClose} title="Authorize with Mastodon">
      <TextInput
        label="Server Domain"
        value={serverName}
        onChange={(event) => setServerName(event.currentTarget.value)}
      />
      <Button loading={loading} onClick={handleClick}>
        Authorize
      </Button>
    </Modal>
  );
};

export const Profile: React.FC = () => {
  const { username, telegram_photo_url, mastodon_server, mastodon_username } =
    useUserContext();
  const [opened, { open, close }] = useDisclosure(false);

  const mastodon_account = React.useMemo(
    () => `@${mastodon_username}@${mastodon_server}`,
    [mastodon_server, mastodon_username],
  );

  return (
    <>
      <Flex align="center" gap="md" mb="xl">
        <Avatar src={telegram_photo_url} size="150" />
        <Title>{username}</Title>
      </Flex>
      <Box mb="md">
        <Link to={`/dashboard`}>Return to dashboard</Link>
      </Box>
      <Paper bg="gray.1">
        <Title order={4}>Mastodon</Title>
        <TextInput label="Account" w="50%" value={mastodon_account} />
        <Button onClick={open}>Authorize with Mastodon</Button>
        <AuthorizeMastodonModal opened={opened} onClose={close} />
      </Paper>
    </>
  );
};
