'use client';
import { signInWithMicrosoft } from '@/lib/actions';
import { StatusMessage, SubmitButton } from '@/components/default';
import { useAuth } from '@/components/context/auth';
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';

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) {
        // Redirect to Microsoft OAuth page
        window.location.href = result.data;
      } else {
        setStatusMessage(`Error: ${result.error}`);
      }
    } 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/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>
  );
};
