import { H2, LoadingOverlay, Paragraph, Button, Theme, YStack, XStack } from '@my/ui'
import { CodeInput } from 'app/utils/auth/codeInput'
import { useSupabase } from 'app/utils/supabase/useSupabase'
import { useUser } from 'app/utils/useUser'
import { useEffect, useState } from 'react'
import { createParam } from 'solito'
import { useRouter } from 'solito/router'

const { useParams, useUpdateParams } = createParam<{ email?: string }>()

export const SignInVerifyScreen = () => {
  const database = useSupabase()
  const router = useRouter()
  const { params } = useParams()
  const updateParams = useUpdateParams()
  const [email, setEmail] = useState(params?.email as string)

  const { isLoadingSession } = useUser()
  const [passcode, setPasscode] = useState('')

  useEffect(() => {
    if (params?.email) {
      updateParams({ email: undefined }, { web: { replace: true } })
    }
  }, [params?.email, updateParams])

  useEffect(() => {
    const signOutListener = database.auth.onAuthStateChange((event) => {
      if (event === 'SIGNED_IN') {
        router.replace('/')
      }
    })
    return () => {
      signOutListener.data.subscription.unsubscribe()
    }
  }, [database, router])

  async function verifyCode() {
    const {
      data: { session },
      error,
    } = await database.auth.verifyOtp({
      email: email,
      token: passcode,
      type: 'email',
    })

    if (error) {
      alert('Verification failed. Please try again.')
    } else {
      router.replace('/')
    }
  }

  return (
    <YStack gap="$3" m="$4">
      <H2 $sm={{ size: '$8' }}>Sign In</H2>
      <Paragraph theme="alt2">
        Please enter the 6-digit code in the email you just received.
      </Paragraph>
      <XStack jc="center" m="$8">
        <CodeInput onChange={setPasscode} codeLength={6} />
      </XStack>
      <Theme inverse>
        <Button onPress={verifyCode} br="$10">
          Verify
        </Button>
      </Theme>
      {isLoadingSession && <LoadingOverlay />}
    </YStack>
  )
}
