import { useCallback, useState } from 'react'
import FeedView from '../components/FeedView.tsx'
import { PostsService } from '../posts/postsService.ts'
import { useUser } from '../../user/userStore.ts'
import { MediaService } from '../../media/mediaService.ts'
import NewPostWidget from '../../../components/NewPostWidget.tsx'
import { useFeedViewModel } from '../components/FeedView.ts'
import { Post } from '../posts/posts.ts'
import { Temporal } from '@js-temporal/polyfill'
import SingleColumnLayout from '../../../layouts/SingleColumnLayout.tsx'
import NavBar from '../../../components/NavBar.tsx'
import AuthNavButtons from '../../auth/components/AuthNavButtons.tsx'

interface HomePageProps {
  postsService: PostsService
  mediaService: MediaService
}

export default function HomePage({ postsService, mediaService }: HomePageProps) {
  const { user } = useUser()
  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.uploadFile(file)

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

  const isLoggedIn = user != null

  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} />
      </main>
    </SingleColumnLayout>
  )
}
