'use client';
import { signInWithApple } from '@/lib/queries';
import {
  StatusMessage,
  SubmitButton,
  type SubmitButtonProps,
} from '@/components/default/forms';
import { useAuth } from '@/lib/hooks/context';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { useSupabaseClient } from '@/utils/supabase';
import { FaApple } from 'react-icons/fa';
import { type ComponentProps } from 'react';
import { cn } from '@/lib/utils';

export type SignInWithAppleProps = {
  submitButtonProps?: SubmitButtonProps;
  formProps?: ComponentProps<'form'>;
  textProps?: ComponentProps<'p'>;
  iconProps?: ComponentProps<'svg'>;
};

export const SignInWithApple = ({
  submitButtonProps,
  formProps,
  textProps,
  iconProps,
} : SignInWithAppleProps) => {
  const router = useRouter();
  const { loading, refreshUser } = useAuth();
  const [statusMessage, setStatusMessage] = useState('');
  const [ isLoading, setIsLoading ] = useState(false);
  const supabase = useSupabaseClient();

  const handleSignInWithApple = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (!supabase) throw new Error('Supabase client not found');
      setStatusMessage('');
      setIsLoading(true);
      const result = await signInWithApple(supabase);
      if (result.data.url) window.location.href = result.data.url;
      else setStatusMessage(`There was a problem signing in with Apple!`);
    } catch (error) {
      setStatusMessage(`Error signing in: ${error as string}`);
    } finally {
      setIsLoading(false);
      await refreshUser();
      router.push('');
    }
  };

  return (
    <form
      {...formProps}
      onSubmit={handleSignInWithApple}
      className={cn('my-4', formProps?.className)}
    >
      <SubmitButton
        disabled={isLoading || loading}
        pendingText='Signing in...'
        {...submitButtonProps}
        className={cn('w-full', submitButtonProps?.className)}
      >
        <div className='flex items-center gap-2'>
          <FaApple {...iconProps} className={cn('size-5', iconProps?.className)} />
          <p {...textProps} className={cn('text-[1.0rem]', textProps?.className)} >
            Sign In with Apple
          </p>
        </div>
  </SubmitButton>
      {statusMessage && <StatusMessage message={{ error: statusMessage }} />}
    </form>
  );
};
