import Sheet from "@/components/sheet/sheet";
import { useAuth } from "@/contexts/auth-context";
import { Flex, Title, ActionIcon } from "@mantine/core";
import { PencilIcon } from "@phosphor-icons/react";
import { useMemo } from "react";
import NameUpdateForm from "./name-form";
import Avatar from "@/components/avatar";
import { useSheet } from "@/hooks/use-sheet";
import { Player } from "../../types";

interface HeaderProps {
  player: Player;
}

const Header = ({ player }: HeaderProps) => {
  const sheet = useSheet();
  const { user: authUser } = useAuth();

  const owner = useMemo(() => authUser?.id === player.id, [authUser?.id, player.id]);
  const name = useMemo(() => `${player.first_name} ${player.last_name}`, [player.first_name, player.last_name]);

  const fontSize = useMemo(() => {
    const baseSize = 28;
    const maxLength = 24;

    if (name.length <= maxLength) {
      return `${baseSize}px`;
    }

    const scaleFactor = Math.max(0.6, maxLength / name.length);
    return `${Math.floor(baseSize * scaleFactor)}px`;
  }, [name]);

  return (
    <>
      <Flex h="15dvh" px='xl' w='100%' align='self-end' gap='md'>
        <Avatar name={name} size={100} />
        <Flex align='center' justify='center' gap={4} pb={20} w='100%'>
          <Title ta='center' style={{ fontSize, lineHeight: 1.2 }}>{name}</Title>
          <ActionIcon display={owner ? 'block' : 'none'} radius='xl' variant='subtle' onClick={sheet.open}>
            <PencilIcon size={20} />
          </ActionIcon>
        </Flex>
      </Flex>

      <Sheet title='Update Name' {...sheet.props}>
        <NameUpdateForm player={player} toggle={sheet.toggle} />
      </Sheet>
    </>
  )
};

export default Header;