'use client';
import { signInWithApple } from '@/lib/actions';
import { StatusMessage, SubmitButton } from '@/components/default';
import { useAuth } from '@/components/context';
import { useRouter } from 'next/navigation';
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 SignInWithAppleProps = {
  className?: ComponentProps<'div'>['className'];
  buttonSize?: VariantProps<typeof buttonVariants>['size'];
  buttonVariant?: VariantProps<typeof buttonVariants>['variant'];
};

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

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

      const result = await signInWithApple();

      if (result?.success && result.data) {
        // Redirect to Apple 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!'}`,
      );
    } finally {
      setIsSigningIn(false);
      await refreshUserData();
      router.push('');
    }
  };

  return (
    <form onSubmit={handleSignInWithApple} 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/apple.svg'
            alt='Apple logo'
            className='invert-75 dark:invert-25'
            width={22}
            height={22}
          />
          <p className='text-[1.0rem]'>Sign In with Apple</p>
        </div>
      </SubmitButton>
      {statusMessage && <StatusMessage message={{ error: statusMessage }} />}
    </form>
  );
};
