'use client';

import React, { ReactElement } from 'react';
import {
  Menu,
  Avatar,
  Text,
  Group,
  UnstyledButton,
  rem,
  Divider,
  Box,
} from '@mantine/core';
import {
  IconLogout,
  IconSettings,
  IconUser,
  IconChevronDown,
} from '@tabler/icons-react';
import { UserButtonProps, UserButtonMenuItemProps, UserButtonLinkProps } from './UserButton.types';
import { useAuth } from '../../hooks/useAuth';
import { useRouter } from 'next/navigation';
import classes from './UserButton.module.css';

// Sub-components
function MenuItems({ children }: { children: ReactNode }) {
  return <>{children}</>;
}

function Link({ children, href, icon, onClick, color, disabled }: UserButtonLinkProps) {
  const router = useRouter();
  
  const handleClick = () => {
    if (onClick) {
      onClick();
    } else {
      router.push(href);
    }
  };

  return (
    <Menu.Item
      leftSection={icon}
      onClick={handleClick}
      color={color}
      disabled={disabled}
    >
      {children}
    </Menu.Item>
  );
}

function Action({ children, onClick, icon, color, disabled }: UserButtonMenuItemProps) {
  return (
    <Menu.Item
      leftSection={icon}
      onClick={onClick}
      color={color}
      disabled={disabled}
    >
      {children}
    </Menu.Item>
  );
}

// Main component
export function UserButton({
  afterSignOutUrl = '/',
  afterMultiSessionSingleSignOutUrl,
  afterSwitchSessionUrl,
  appearance,
  showName = false,
  children,
  className,
  style,
}: UserButtonProps) {
  const { user, signOut } = useAuth();
  const router = useRouter();

  if (!user) {
    return null;
  }

  const handleSignOut = async () => {
    await signOut();
    router.push(afterSignOutUrl);
  };

  const displayName = user.displayName || user.email?.split('@')[0] || 'User';
  const avatarUrl = user.photoURL || undefined;
  const initials = displayName
    .split(' ')
    .map(n => n[0])
    .join('')
    .toUpperCase()
    .slice(0, 2);

  // Extract custom menu items from children
  let customMenuItems: ReactElement[] = [];
  if (children) {
    React.Children.forEach(children, (child) => {
      if (React.isValidElement(child) && child.type === MenuItems) {
        React.Children.forEach(child.props.children, (menuItem) => {
          if (React.isValidElement(menuItem)) {
            customMenuItems.push(menuItem);
          }
        });
      }
    });
  }

  return (
    <Menu
      width={260}
      position="bottom-end"
      transitionProps={{ transition: 'pop-top-right' }}
      withinPortal
    >
      <Menu.Target>
        <UnstyledButton
          className={`${classes.user} ${className || ''}`}
          style={style}
        >
          <Group gap={7}>
            <Avatar
              src={avatarUrl}
              alt={displayName}
              radius="xl"
              size={28}
              className={appearance?.elements?.avatarBox}
            >
              {!avatarUrl && initials}
            </Avatar>
            {showName && (
              <>
                <Text fw={500} size="sm" lh={1} mr={3}>
                  {displayName}
                </Text>
                <IconChevronDown size={rem(12)} stroke={1.5} />
              </>
            )}
          </Group>
        </UnstyledButton>
      </Menu.Target>

      <Menu.Dropdown>
        <Box px="xs" py="sm">
          <Group>
            <Avatar
              src={avatarUrl}
              alt={displayName}
              radius="xl"
              size={40}
            >
              {!avatarUrl && initials}
            </Avatar>
            <div style={{ flex: 1 }}>
              <Text size="sm" fw={500}>
                {displayName}
              </Text>
              <Text c="dimmed" size="xs">
                {user.email}
              </Text>
            </div>
          </Group>
        </Box>

        <Divider />

        <Menu.Item
          leftSection={<IconUser size={rem(14)} stroke={1.5} />}
          onClick={() => router.push('/user-profile')}
        >
          Manage account
        </Menu.Item>

        {customMenuItems.length > 0 && (
          <>
            <Divider />
            {customMenuItems}
          </>
        )}

        <Divider />

        <Menu.Item
          leftSection={<IconLogout size={rem(14)} stroke={1.5} />}
          onClick={handleSignOut}
          color="red"
        >
          Sign out
        </Menu.Item>
      </Menu.Dropdown>
    </Menu>
  );
}

// Attach sub-components
UserButton.MenuItems = MenuItems;
UserButton.Link = Link;
UserButton.Action = Action;