import { Separator, Spinner, View, YStack, useWindowDimensions, Button, XStack } from '@my/ui'
import { Menu, Camera } from '@tamagui/lucide-icons'
import { CardProps } from 'app/types'
import { useSupabase } from 'app/utils/supabase/useSupabase'
import { useUser } from 'app/utils/useUser'
import { useEffect, useState } from 'react'
import { FlatList } from 'react-native'
import uuid from 'react-native-uuid'
import { useRouter } from 'solito/router'

import { MemberGreetingCard } from './MemberGreetingCard'
import { VisitorGuideCard } from './VisitorGuideCard'
import { JunwonLogoIcon } from '../../assets/icon'
import { Card } from '../card/card'
import { SearchBar } from '../search/search'

const contentOffset = 24

async function getDataFromServer(database, offset = 0, limit = 5): Promise<CardProps[]> {
  const randomUUID = uuid.v4()

  const { data: dataFromServer, error } = await database
    .from('cards')
    .select('*')
    .eq('is_discovery_card', true)
    .eq('is_presentable', true)
    .gt('id', randomUUID)
    .order('id')
    .range(offset, offset + limit - 1)
  if (error) {
    console.error('Error getting data from server:', error)
    return []
  }
  return dataFromServer.map((item) => ({ ...item, showElaborateOption: true }))
}

async function verifyAuthToken(database) {
  const urlParams = new URLSearchParams(window.location.search)
  const token_hash = urlParams.get('token_hash')
  const type = urlParams.get('type') === 'email' ? 'email' : 'mobile'

  if (token_hash && type) {
    await database.auth.verifyOtp({ token_hash, type: 'email' })
  }
}

export function HomeScreen() {
  const [data, setData] = useState<CardProps[]>([])
  const [loading, setLoading] = useState(false)
  const [offset, setOffset] = useState(0)
  const dimensions = useWindowDimensions()
  const database = useSupabase()
  const { profile, user, saveCardToMemberCollection, unsaveCardFromMemberCollection } = useUser()
  const router = useRouter()

  const isCardInMemberCollection = (cardId: string) => {
    return profile?.collection?.inbox?.includes(cardId) || false
  }

  const insertDataAfterIndex = (newData, index) => {
    const newDataWithoutElaborateOption = newData.map((item) => ({
      ...item,
      showElaborateOption: false,
    }))
    setData((prevData) => [
      ...prevData.slice(0, index + 1),
      ...newDataWithoutElaborateOption,
      ...prevData.slice(index + 1),
    ])
  }

  const fetchMoreData = async () => {
    if (loading) return
    setLoading(true)
    const newItems = await getDataFromServer(database, offset)
    if (newItems.length > 0) {
      setOffset(offset + newItems.length)
      setData((prevData) => [...prevData, ...newItems])
    }
    setLoading(false)
  }

  useEffect(() => {
    const fetchData = async () => {
      await verifyAuthToken(database)
      setLoading(true)
      const initialData = await getDataFromServer(database)
      const greetingCard = user ? MemberGreetingCard() : VisitorGuideCard()
      setData([greetingCard, ...initialData])
      setLoading(false)
    }

    fetchData()
  }, [user, database])

  return (
    <View style={{ flex: 1 }}>
      <FlatList
        style={{ height: dimensions.height, width: dimensions.width }}
        data={data}
        keyExtractor={(item, index) => index.toString()}
        ListHeaderComponent={
          <YStack
            width={dimensions.width - 2 * contentOffset}
            maxWidth={500}
            ai="center"
            m="$8"
            gap="$8"
          >
            <XStack width="100%" ai="center" jc="space-between">
              <Button
                icon={Menu}
                size="$6"
                p="$5"
                chromeless
                pressStyle={{ backgroundColor: 'transparent', borderColor: 'transparent' }}
                onPress={() => router.push('/control')}
              />
              <View style={{ flex: 1, alignItems: 'center' }}>
                <JunwonLogoIcon />
              </View>
              <Button
                icon={Camera}
                size="$6"
                chromeless
                p="$5"
                pressStyle={{ backgroundColor: 'transparent', borderColor: 'transparent' }}
                onPress={() => router.push('/camera')}
              />
            </XStack>
            <SearchBar database={database} insertDataAfterIndex={insertDataAfterIndex} />
          </YStack>
        }
        renderItem={({ item, index }) => {
          const isInMemberCollection = isCardInMemberCollection(item.id)
          return (
            <YStack>
              <Card
                card={{ ...item, is_in_member_collection: isInMemberCollection }}
                database={database}
                insertDataAfterIndex={insertDataAfterIndex}
                indexInList={index}
                saveCardToMemberCollection={saveCardToMemberCollection}
                unsaveCardFromMemberCollection={unsaveCardFromMemberCollection}
              />
              <Separator w="100%" als="center" m="$6" />
            </YStack>
          )
        }}
        contentContainerStyle={{ alignItems: 'center' }}
        onEndReached={fetchMoreData}
        onEndReachedThreshold={0.5}
        ListFooterComponent={<Spinner size="large" color="#fff" mb="$6" />}
      />
    </View>
  )
}
