import { useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import type { ArticleFilters } from '@/components/ArticleFilters'
import type { NostrProfile } from '@/types/nostr'
import { ProfileView } from '@/components/ProfileView'
import { useNostrConnect } from '@/hooks/useNostrConnect'
import { useUserArticles } from '@/hooks/useUserArticles'
import { nostrService } from '@/lib/nostr'

function useUserProfileData(currentPubkey: string | null) {
  const [profile, setProfile] = useState<NostrProfile | null>(null)
  const [loadingProfile, setLoadingProfile] = useState(true)

  useEffect(() => {
    if (!currentPubkey) {
      return
    }

    const createMinimalProfile = (): NostrProfile => ({
      pubkey: currentPubkey,
    })

    const load = async () => {
      try {
        const loadedProfile = await nostrService.getProfile(currentPubkey)
        setProfile(loadedProfile ?? createMinimalProfile())
      } catch (e) {
        console.error('Error loading profile:', e)
        setProfile(createMinimalProfile())
      } finally {
        setLoadingProfile(false)
      }
    }

    setLoadingProfile(true)
    void load()
  }, [currentPubkey])

  return { profile, loadingProfile }
}

function useRedirectWhenDisconnected(connected: boolean, pubkey: string | null) {
  const router = useRouter()
  useEffect(() => {
    if (!connected || !pubkey) {
      void router.push('/')
    }
  }, [connected, pubkey, router])
}

function useProfileController() {
  const { connected, pubkey: currentPubkey } = useNostrConnect()
  const [searchQuery, setSearchQuery] = useState('')
  const [filters, setFilters] = useState<ArticleFilters>({
    authorPubkey: null,
    sortBy: 'newest',
    category: 'all',
  })
  const [selectedSeriesId, setSelectedSeriesId] = useState<string | undefined>(undefined)

  useRedirectWhenDisconnected(connected, currentPubkey ?? null)
  const { profile, loadingProfile } = useUserProfileData(currentPubkey ?? null)

  const { articles, allArticles, loading, error, loadArticleContent } = useUserArticles(
    currentPubkey ?? '',
    searchQuery,
    filters
  )

  return {
    connected,
    currentPubkey,
    searchQuery,
    setSearchQuery,
    filters,
    setFilters,
    articles,
    allArticles,
    loading,
    error,
    loadArticleContent,
    profile,
    loadingProfile,
    selectedSeriesId,
    onSelectSeries: setSelectedSeriesId,
  }
}

export default function ProfilePage() {
  const controller = useProfileController()
  const { connected, currentPubkey } = controller

  useRedirectWhenDisconnected(connected, currentPubkey ?? null)

  if (!connected || !currentPubkey) {
    return null
  }

  return (
    <ProfileView
      {...controller}
      currentPubkey={currentPubkey}
    />
  )
}
