'use client';

import React, { useState } from 'react';
import {
  Paper,
  TextInput,
  PasswordInput,
  Button,
  Stack,
  Text,
  Divider,
  Group,
  Anchor,
  Checkbox,
  Alert,
  Title,
  Container,
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { IconAlertCircle, IconBrandGoogle, IconBrandGithub } from '@tabler/icons-react';
import { SignInProps, SignInFormData } from './SignIn.types';
import { useAuth } from '../../hooks/useAuth';
import { useRouter } from 'next/navigation';

export function SignIn({
  redirectUrl = '/dashboard',
  afterSignInUrl,
  providers = ['email', 'google', 'github'],
  appearance,
  onSuccess,
  onError,
  rememberMe = true,
  showDivider = true,
  forgotPasswordUrl = '/forgot-password',
  signUpUrl = '/sign-up',
  initialEmail = '',
  className,
  style,
}: SignInProps) {
  const router = useRouter();
  const { signIn, signInWithGoogle, signInWithGithub } = useAuth();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const form = useForm<SignInFormData>({
    initialValues: {
      email: initialEmail,
      password: '',
      rememberMe: false,
    },
    validate: {
      email: (value) => (!value ? 'Email is required' : !/^\S+@\S+$/.test(value) ? 'Invalid email' : null),
      password: (value) => (!value ? 'Password is required' : value.length < 6 ? 'Password must be at least 6 characters' : null),
    },
  });

  const handleSubmit = async (values: SignInFormData) => {
    setLoading(true);
    setError(null);

    try {
      const user = await signIn(values.email, values.password, values.rememberMe);
      
      if (onSuccess) {
        onSuccess(user);
      }
      
      const redirectTo = afterSignInUrl || redirectUrl;
      router.push(redirectTo);
    } catch (err: any) {
      const errorMessage = err.message || 'Failed to sign in';
      setError(errorMessage);
      
      if (onError) {
        onError(err);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleSocialSignIn = async (provider: 'google' | 'github') => {
    setLoading(true);
    setError(null);

    try {
      let user;
      if (provider === 'google') {
        user = await signInWithGoogle();
      } else {
        user = await signInWithGithub();
      }
      
      if (onSuccess) {
        onSuccess(user);
      }
      
      const redirectTo = afterSignInUrl || redirectUrl;
      router.push(redirectTo);
    } catch (err: any) {
      const errorMessage = err.message || `Failed to sign in with ${provider}`;
      setError(errorMessage);
      
      if (onError) {
        onError(err);
      }
    } finally {
      setLoading(false);
    }
  };

  const socialButtons = providers.includes('google') || providers.includes('github') ? (
    <Stack>
      {providers.includes('google') && (
        <Button
          leftSection={<IconBrandGoogle size={20} />}
          variant="default"
          fullWidth
          onClick={() => handleSocialSignIn('google')}
          disabled={loading}
        >
          Continue with Google
        </Button>
      )}
      {providers.includes('github') && (
        <Button
          leftSection={<IconBrandGithub size={20} />}
          variant="default"
          fullWidth
          onClick={() => handleSocialSignIn('github')}
          disabled={loading}
        >
          Continue with GitHub
        </Button>
      )}
    </Stack>
  ) : null;

  const showSocialTop = appearance?.layout?.socialButtonsPlacement === 'top';

  return (
    <Container size={420} className={className} style={style}>
      <Paper withBorder shadow="md" p={30} radius="md">
        <Title order={2} ta="center" mb={5}>
          Welcome back
        </Title>
        <Text c="dimmed" size="sm" ta="center" mb={20}>
          Sign in to your account to continue
        </Text>

        {error && (
          <Alert icon={<IconAlertCircle size={16} />} color="red" mb="md">
            {error}
          </Alert>
        )}

        {showSocialTop && socialButtons}
        {showSocialTop && showDivider && providers.includes('email') && (
          <Divider label="Or continue with email" labelPosition="center" my="lg" />
        )}

        {providers.includes('email') && (
          <form onSubmit={form.onSubmit(handleSubmit)}>
            <Stack>
              <TextInput
                label="Email"
                placeholder="your@email.com"
                required
                {...form.getInputProps('email')}
                disabled={loading}
              />

              <PasswordInput
                label="Password"
                placeholder="Your password"
                required
                {...form.getInputProps('password')}
                disabled={loading}
              />

              <Group justify="space-between">
                {rememberMe && (
                  <Checkbox
                    label="Remember me"
                    {...form.getInputProps('rememberMe', { type: 'checkbox' })}
                    disabled={loading}
                  />
                )}
                <Anchor size="sm" href={forgotPasswordUrl}>
                  Forgot password?
                </Anchor>
              </Group>

              <Button type="submit" fullWidth loading={loading}>
                Sign in
              </Button>
            </Stack>
          </form>
        )}

        {!showSocialTop && showDivider && socialButtons && providers.includes('email') && (
          <Divider label="Or continue with" labelPosition="center" my="lg" />
        )}
        {!showSocialTop && socialButtons}

        <Text c="dimmed" size="sm" ta="center" mt={20}>
          Don&apos;t have an account?{' '}
          <Anchor size="sm" href={signUpUrl}>
            Sign up
          </Anchor>
        </Text>
      </Paper>
    </Container>
  );
}