'use server';
import { signInWithApple } from '@/lib/queries';
import {
  SubmitButton,
  type SubmitButtonProps,
} from '@/components/default/forms';
import { SupabaseServer } from '@/utils/supabase';
import { FaApple } from 'react-icons/fa';
import { type ComponentProps } from 'react';
import { cn } from '@/lib/utils';

export type SignInWithAppleProps = {
  submitButtonProps?: SubmitButtonProps;
  formClassName?: ComponentProps<'form'>['className'];
  formProps?: Omit<ComponentProps<'form'>, 'className'>;
  textClassName?: ComponentProps<'p'>['className'];
  textProps?: Omit<ComponentProps<'p'>, 'className'>;
  iconClassName?: ComponentProps<'svg'>['className'];
  iconProps?: Omit<ComponentProps<'svg'>, 'className'>;
};

export const SignInWithApple = async ({
  submitButtonProps,
  formClassName,
  formProps,
  textClassName,
  textProps,
  iconClassName,
  iconProps,
} : SignInWithAppleProps) => {
  const supabase = await SupabaseServer();

  const handleSignInWithApple = async () => {
    try {
      if (!supabase) throw new Error('Supabase client not found');
      const result = await signInWithApple(supabase);
      if (result.error)
        throw new Error(`Error signing in with Microsoft: ${result.error.message}`);
      else if (result.data.url) window.location.href = result.data.url;
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <form
      action={handleSignInWithApple}
      className={cn('my-4', formClassName)}
      {...formProps}
    >
      <SubmitButton
        pendingText='Signing in...'
        className={cn('w-full', submitButtonProps?.className)}
        {...submitButtonProps}
      >
        <div className='flex items-center gap-2'>
          <FaApple className={cn('size-5', iconClassName)} {...iconProps} />
          <p className={cn('text-[1.0rem]', textClassName)} {...textProps}>
            Sign In with Apple
          </p>
        </div>
      </SubmitButton>
    </form>
  );
};
