import { Separator, Spinner, View, YStack, useWindowDimensions } from '@my/ui'
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 { useLink } from 'solito/link'

import { EmptyCollectionCard } from './EmptyCollectionCard'
import { JunwonLogoIcon } from '../../assets/icon'
import { Card } from '../card/card'

const contentOffset = 24

export function CollectionScreen() {
  const [data, setData] = useState<CardProps[]>([])
  const [loading, setLoading] = useState(true)
  const [allDataFetched, setAllDataFetched] = useState(false)
  const dimensions = useWindowDimensions()
  const database = useSupabase()
  const {
    profile,
    saveCardToMemberCollection,
    unsaveCardFromMemberCollection,
    getCardsInMemberCollection,
  } = useUser()

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

  const isCollectionEmpty = !profile?.collection?.inbox || profile.collection.inbox.length === 0

  useEffect(() => {
    const fetchData = async () => {
      if (allDataFetched) return
      setLoading(true)
      const collectionData = await getCardsInMemberCollection()
      setData(collectionData)
      setLoading(false)
      setAllDataFetched(true)
    }
    if (isCollectionEmpty) {
      setLoading(false)
      setAllDataFetched(true)
    } else {
      fetchData()
    }
  }, [getCardsInMemberCollection, isCollectionEmpty, allDataFetched])

  return (
    <View style={{ flex: 1 }}>
      <FlatList
        style={{ height: dimensions.height, width: dimensions.width }}
        data={isCollectionEmpty ? [EmptyCollectionCard()] : data}
        keyExtractor={(item) => item.id}
        ListHeaderComponent={
          <YStack
            width={dimensions.width - 2 * contentOffset}
            maxWidth={500}
            ai="center"
            m="$8"
            gap="$8"
          >
            <View {...useLink({ href: '/control' })}>
              <JunwonLogoIcon />
            </View>
          </YStack>
        }
        renderItem={({ item, index }) => {
          if (isCollectionEmpty) {
            return (
              <Card
                card={item}
                database={database}
                insertDataAfterIndex={() => {}}
                indexInList={index}
                saveCardToMemberCollection={saveCardToMemberCollection}
                unsaveCardFromMemberCollection={unsaveCardFromMemberCollection}
              />
            )
          }
          const isInMemberCollection = isCardInMemberCollection(item.id)
          return (
            <YStack>
              <Card
                card={{ ...item, is_in_member_collection: isInMemberCollection }}
                database={database}
                insertDataAfterIndex={() => {}}
                indexInList={index}
                saveCardToMemberCollection={saveCardToMemberCollection}
                unsaveCardFromMemberCollection={unsaveCardFromMemberCollection}
              />
              <Separator w="100%" als="center" m="$6" />
            </YStack>
          )
        }}
        contentContainerStyle={{ alignItems: 'center' }}
        ListFooterComponent={loading ? <Spinner size="large" color="#fff" mb="$6" /> : null}
      />
    </View>
  )
}
