import { H2, LoadingOverlay, Paragraph, SubmitButton, Theme, YStack } from '@my/ui'
import { getBaseUrl } from 'app/utils/getBaseUrl'
import { SchemaForm, formFields } from 'app/utils/SchemaForm'
import { useSupabase } from 'app/utils/supabase/useSupabase'
import { useUser } from 'app/utils/useUser'
import { useState } from 'react'
import { FormProvider, useForm } from 'react-hook-form'
import { useRouter } from 'solito/router'
import { z } from 'zod'

const SignInSchema = z.object({
  email: formFields.text.email().describe('Email // Enter your email'),
})

export const SignInScreen = () => {
  const database = useSupabase()
  const router = useRouter()
  const { isLoadingSession } = useUser()
  const [email, setEmail] = useState('')
  const form = useForm<z.infer<typeof SignInSchema>>()
  const baseUrl = getBaseUrl()

  async function signInWithEmail({ email }: z.infer<typeof SignInSchema>) {
    const { error } = await database.auth.signInWithOtp({
      email,
      options: {
        emailRedirectTo: baseUrl
      },
    })

    if (error) {
      form.setError('email', { type: 'custom', message: "Failed to send passcode. Please check your email." })
    } else {
      setEmail(email)
      router.push(`/sign-in-verify?email=${encodeURIComponent(email)}`)
    }
  }

  return (
    <FormProvider {...form}>
      <SchemaForm
        form={form}
        schema={SignInSchema}
        defaultValues={{
          email: email,
        }}
        onSubmit={signInWithEmail}
        renderAfter={({ submit }) => (
          <Theme inverse>
            <SubmitButton onPress={() => submit()} br="$10">
              Send Code
            </SubmitButton>
          </Theme>
        )}
      >
        {(fields) => (
          <>
            <YStack gap="$3" mb="$4">
              <H2 $sm={{ size: '$8' }}>Sign In</H2>
              <Paragraph theme="alt2">
                What is your email? I will send you a code with which you can sign in (or a sign up link if you do not have an account). 
              </Paragraph>
            </YStack>
            {Object.values(fields)}
          </>
        )}
      </SchemaForm>
      {isLoadingSession && <LoadingOverlay />}
    </FormProvider>
  )
}