'use client';

import React, { useState, ReactElement } from 'react';
import {
  Container,
  Paper,
  Tabs,
  Stack,
  Title,
  Text,
  Avatar,
  Group,
  TextInput,
  Button,
  PasswordInput,
  Alert,
  Box,
  rem,
} from '@mantine/core';
import {
  IconUser,
  IconLock,
  IconSettings,
  IconAlertCircle,
  IconCheck,
} from '@tabler/icons-react';
import { useForm } from '@mantine/form';
import { UserProfileProps, UserProfilePageProps } from './UserProfile.types';
import { useUser } from '../../hooks/useUser';
import { notifications } from '@mantine/notifications';

// Sub-component for custom pages
function Page({ label, labelIcon, children }: UserProfilePageProps) {
  return <div data-label={label}>{children}</div>;
}

export function UserProfile({
  appearance,
  children,
  className,
  style,
}: UserProfileProps) {
  const { user, refreshUser } = useUser();
  const [activeTab, setActiveTab] = useState<string | null>('profile');
  const [loading, setLoading] = useState(false);

  // Extract custom pages from children
  const customPages: Array<{ label: string; icon?: ReactNode; content: ReactNode }> = [];
  if (children) {
    React.Children.forEach(children, (child) => {
      if (React.isValidElement(child) && child.type === Page) {
        const pageProps = child.props as UserProfilePageProps;
        customPages.push({
          label: pageProps.label,
          icon: pageProps.labelIcon,
          content: pageProps.children,
        });
      }
    });
  }

  const profileForm = useForm({
    initialValues: {
      displayName: user?.displayName || '',
      email: user?.email || '',
    },
  });

  const passwordForm = useForm({
    initialValues: {
      currentPassword: '',
      newPassword: '',
      confirmPassword: '',
    },
    validate: {
      newPassword: (value) => {
        if (!value) return 'New password is required';
        if (value.length < 8) return 'Password must be at least 8 characters';
        return null;
      },
      confirmPassword: (value, values) =>
        value !== values.newPassword ? 'Passwords do not match' : null,
    },
  });

  const handleProfileUpdate = async (values: any) => {
    setLoading(true);
    try {
      // Update profile logic here
      await refreshUser();
      notifications.show({
        title: 'Profile updated',
        message: 'Your profile has been updated successfully',
        color: 'green',
        icon: <IconCheck size={16} />,
      });
    } catch (error: any) {
      notifications.show({
        title: 'Update failed',
        message: error.message || 'Failed to update profile',
        color: 'red',
        icon: <IconAlertCircle size={16} />,
      });
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordUpdate = async (values: any) => {
    setLoading(true);
    try {
      // Update password logic here
      notifications.show({
        title: 'Password updated',
        message: 'Your password has been updated successfully',
        color: 'green',
        icon: <IconCheck size={16} />,
      });
      passwordForm.reset();
    } catch (error: any) {
      notifications.show({
        title: 'Update failed',
        message: error.message || 'Failed to update password',
        color: 'red',
        icon: <IconAlertCircle size={16} />,
      });
    } finally {
      setLoading(false);
    }
  };

  if (!user) {
    return null;
  }

  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);

  return (
    <Container size="md" className={className} style={style}>
      <Paper shadow="sm" radius="md" p="lg">
        <Stack>
          <Box>
            <Group mb="md">
              <Avatar
                src={avatarUrl}
                alt={displayName}
                radius="xl"
                size="xl"
              >
                {!avatarUrl && initials}
              </Avatar>
              <div>
                <Title order={3}>{displayName}</Title>
                <Text c="dimmed" size="sm">{user.email}</Text>
              </div>
            </Group>
          </Box>

          <Tabs value={activeTab} onChange={setActiveTab}>
            <Tabs.List>
              <Tabs.Tab value="profile" leftSection={<IconUser size={rem(16)} />}>
                Profile
              </Tabs.Tab>
              <Tabs.Tab value="security" leftSection={<IconLock size={rem(16)} />}>
                Security
              </Tabs.Tab>
              {customPages.map((page, index) => (
                <Tabs.Tab
                  key={index}
                  value={`custom-${index}`}
                  leftSection={page.icon}
                >
                  {page.label}
                </Tabs.Tab>
              ))}
            </Tabs.List>

            <Tabs.Panel value="profile" pt="md">
              <form onSubmit={profileForm.onSubmit(handleProfileUpdate)}>
                <Stack>
                  <TextInput
                    label="Display name"
                    placeholder="Your name"
                    {...profileForm.getInputProps('displayName')}
                    disabled={loading}
                  />
                  
                  <TextInput
                    label="Email"
                    placeholder="your@email.com"
                    {...profileForm.getInputProps('email')}
                    disabled
                  />

                  <Group>
                    <Button type="submit" loading={loading}>
                      Update profile
                    </Button>
                  </Group>
                </Stack>
              </form>
            </Tabs.Panel>

            <Tabs.Panel value="security" pt="md">
              <form onSubmit={passwordForm.onSubmit(handlePasswordUpdate)}>
                <Stack>
                  <PasswordInput
                    label="Current password"
                    placeholder="Enter current password"
                    {...passwordForm.getInputProps('currentPassword')}
                    disabled={loading}
                  />
                  
                  <PasswordInput
                    label="New password"
                    placeholder="Enter new password"
                    {...passwordForm.getInputProps('newPassword')}
                    disabled={loading}
                  />
                  
                  <PasswordInput
                    label="Confirm new password"
                    placeholder="Confirm new password"
                    {...passwordForm.getInputProps('confirmPassword')}
                    disabled={loading}
                  />

                  <Group>
                    <Button type="submit" loading={loading}>
                      Update password
                    </Button>
                  </Group>
                </Stack>
              </form>
            </Tabs.Panel>

            {customPages.map((page, index) => (
              <Tabs.Panel key={index} value={`custom-${index}`} pt="md">
                {page.content}
              </Tabs.Panel>
            ))}
          </Tabs>
        </Stack>
      </Paper>
    </Container>
  );
}

// Attach sub-component
UserProfile.Page = Page;