'use client';
import { signInWithMicrosoft } from '@/lib/actions';
import { StatusMessage, SubmitButton } from '@/components/default';
import { useAuth } from '@/components/context';
import { useState } from 'react';
import Image from 'next/image';
import { type buttonVariants } from '@/components/ui';
import { type ComponentProps } from 'react';
import { type VariantProps } from 'class-variance-authority';
import { getProfile, updateProfile } from '@/lib/hooks';

type SignInWithMicrosoftProps = {
  className?: ComponentProps<'div'>['className'];
  buttonSize?: VariantProps<typeof buttonVariants>['size'];
  buttonVariant?: VariantProps<typeof buttonVariants>['variant'];
};

export const SignInWithMicrosoft = ({
  className = 'my-4',
  buttonSize = 'default',
  buttonVariant = 'default',
}: SignInWithMicrosoftProps) => {
  const { isLoading } = useAuth();
  const [statusMessage, setStatusMessage] = useState('');
  const [isSigningIn, setIsSigningIn] = useState(false);

  const handleSignInWithMicrosoft = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      setStatusMessage('');
      setIsSigningIn(true);

      const result = await signInWithMicrosoft();

      if (result?.success && result.data) {
        const profileResponse = await getProfile();
        if (profileResponse.success) {
          const profile = profileResponse.data;
          if (!profile.provider) {
            const updateResponse = await updateProfile({
              provider: result.data.provider,
            });
            if (!updateResponse.success)
              throw new Error('Could not update provider!');
          } else {
            const updateResponse = await updateProfile({
              provider: profile.provider + ' ' + result.data.provider,
            });
            if (!updateResponse.success)
              throw new Error('Could not update provider!');
          }
        }
        window.location.href = result.data.url;
      } else {
        setStatusMessage(`Error: Could not sign in with Microsoft!`);
      }
    } catch (error) {
      setStatusMessage(
        `Error: ${error instanceof Error ? error.message : 'Could not sign in!'}`,
      );
    }
  };

  return (
    <form onSubmit={handleSignInWithMicrosoft} className={className}>
      <SubmitButton
        size={buttonSize}
        variant={buttonVariant}
        className='w-full cursor-pointer'
        disabled={isLoading || isSigningIn}
        pendingText='Redirecting...'
        type='submit'
      >
        <div className='flex items-center gap-2'>
          <Image
            src='/icons/auth/microsoft.svg'
            alt='Microsoft logo'
            width={20}
            height={20}
          />
          <p className='text-[1.0rem]'>Sign In with Microsoft</p>
        </div>
      </SubmitButton>
      {statusMessage && <StatusMessage message={{ error: statusMessage }} />}
    </form>
  );
};
