import { useCallback, useState } from 'react'
import FeedView from '../components/FeedView.tsx'
import { PostsService } from '../posts/postsService.ts'
import { useUser } from '../../user/user.ts'
import { MediaService } from '../../media/mediaService.ts'
import NewPostWidget from '../../../components/NewPostWidget.tsx'
import { useFeedViewModel } from '../components/FeedView.ts'
import SingleColumnLayout from '../../../layouts/SingleColumnLayout.tsx'
import NavBar from '../../../components/NavBar.tsx'
import AuthNavButtons from '../../auth/components/AuthNavButtons.tsx'
import { useSaveSignupCodeToLocalStorage } from '../../../hooks/useSaveSignupCodeToLocalStorage.ts'

interface HomePageProps {
  postsService: PostsService
  mediaService: MediaService
}

export default function HomePage({ postsService, mediaService }: HomePageProps) {
  const user = useUser()
  useSaveSignupCodeToLocalStorage()
  const [isSubmitting, setIsSubmitting] = useState(false)

  const fetchPosts = useCallback(
    async (cursor: string | null, amount: number | null) => {
      return postsService.loadPublicFeed(cursor, amount)
    },
    [postsService],
  )

  const { pages, setPages, loadNextPage } = useFeedViewModel(fetchPosts)

  const onCreatePost = useCallback(
    async (
      content: string,
      files: { file: File; width: number; height: number }[],
      isPublic: boolean,
    ) => {
      setIsSubmitting(true)
      if (user == null) throw new Error('Not logged in')
      try {
        const media = await Promise.all(
          files.map(async ({ file, width, height }) => {
            const { mediaId, url } = await mediaService.uploadImage(file)

            return {
              mediaId,
              url,
              width,
              height,
            }
          }),
        )
        const post = await postsService.createNew(user.id, content, media, isPublic)
        setPages((pages) => [[post], ...pages])
      } catch (error) {
        console.error('Failed to create post:', error)
      } finally {
        setIsSubmitting(false)
      }
    },
    [mediaService, postsService, setPages, user],
  )

  const isLoggedIn = user != null

  const addReaction = async (postId: string, emoji: string) => {
    await postsService.addReaction(postId, emoji)
  }

  const clearReaction = async (postId: string, emoji: string) => {
    await postsService.removeReaction(postId, emoji)
  }

  return (
    <SingleColumnLayout
      navbar={
        <NavBar>
          <AuthNavButtons />
        </NavBar>
      }
    >
      <main className={`w-full max-w-3xl mx-auto`}>
        {isLoggedIn && <NewPostWidget onSubmit={onCreatePost} isSubmitting={isSubmitting} />}
        <FeedView
          pages={pages}
          onLoadMore={loadNextPage}
          addReaction={addReaction}
          clearReaction={clearReaction}
        />
      </main>
    </SingleColumnLayout>
  )
}
