import { useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import Head from 'next/head'
import { ConnectButton } from '@/components/ConnectButton'
import { UserProfile } from '@/components/UserProfile'
import { UserArticles } from '@/components/UserArticles'
import { SearchBar } from '@/components/SearchBar'
import { ArticleFiltersComponent, type ArticleFilters } from '@/components/ArticleFilters'
import { useNostrConnect } from '@/hooks/useNostrConnect'
import { useUserArticles } from '@/hooks/useUserArticles'
import { nostrService } from '@/lib/nostr'
import type { NostrProfile } from '@/types/nostr'

export default function ProfilePage() {
  const router = useRouter()
  const { connected, pubkey: currentPubkey } = useNostrConnect()
  const [profile, setProfile] = useState<NostrProfile | null>(null)
  const [loadingProfile, setLoadingProfile] = useState(true)
  const [searchQuery, setSearchQuery] = useState('')
  const [filters, setFilters] = useState<ArticleFilters>({
    authorPubkey: null,
    minPrice: null,
    maxPrice: null,
    sortBy: 'newest',
  })

  // Use current user's pubkey if connected, otherwise redirect
  useEffect(() => {
    if (!connected || !currentPubkey) {
      router.push('/')
      return
    }
  }, [connected, currentPubkey, router])

  // Load user profile
  useEffect(() => {
    if (!currentPubkey) return

    setLoadingProfile(true)
    nostrService
      .getProfile(currentPubkey)
      .then((loadedProfile) => {
        if (loadedProfile) {
          setProfile(loadedProfile)
        } else {
          // Create minimal profile if none exists
          setProfile({
            pubkey: currentPubkey,
            name: undefined,
            about: undefined,
            picture: undefined,
            nip05: undefined,
          })
        }
      })
      .catch((e) => {
        console.error('Error loading profile:', e)
        // Create minimal profile on error
        setProfile({
          pubkey: currentPubkey,
          name: undefined,
          about: undefined,
          picture: undefined,
          nip05: undefined,
        })
      })
      .finally(() => {
        setLoadingProfile(false)
      })
  }, [currentPubkey])

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

  if (!connected || !currentPubkey) {
    return null // Will redirect
  }

  return (
    <>
      <Head>
        <title>My Profile - Nostr Paywall</title>
        <meta name="description" content="View your profile and published articles" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
      </Head>

      <main className="min-h-screen bg-gray-50">
        <header className="bg-white shadow-sm">
          <div className="max-w-4xl mx-auto px-4 py-4 flex justify-between items-center">
            <h1 className="text-2xl font-bold text-gray-900">Nostr Paywall</h1>
            <div className="flex items-center gap-4">
              <a
                href="/publish"
                className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors"
              >
                Publish Article
              </a>
              <ConnectButton />
            </div>
          </div>
        </header>

        <div className="max-w-4xl mx-auto px-4 py-8">
          <div className="mb-6">
            <button
              onClick={() => router.push('/')}
              className="text-blue-600 hover:text-blue-700 text-sm font-medium mb-4"
            >
              ← Back to Articles
            </button>
          </div>

          {/* Profile Section */}
          {loadingProfile ? (
            <div className="text-center py-12">
              <p className="text-gray-500">Loading profile...</p>
            </div>
          ) : profile ? (
            <UserProfile profile={profile} pubkey={currentPubkey} articleCount={allArticles.length} />
          ) : null}

          {/* Search and Filters */}
          <div className="mb-6">
            <h2 className="text-2xl font-bold mb-4">My Articles</h2>
            <div className="mb-4">
              <SearchBar value={searchQuery} onChange={setSearchQuery} placeholder="Search my articles..." />
            </div>
            {!loading && allArticles.length > 0 && (
              <ArticleFiltersComponent
                filters={filters}
                onFiltersChange={setFilters}
                articles={allArticles}
              />
            )}
          </div>

          {/* Articles Count */}
          {!loading && articles.length > 0 && (
            <div className="mb-4 text-sm text-gray-600">
              Showing {articles.length} of {allArticles.length} article{allArticles.length !== 1 ? 's' : ''}
            </div>
          )}

          {/* Articles List */}
          <UserArticles
            articles={articles}
            loading={loading}
            error={error}
            onLoadContent={loadArticleContent}
            showEmptyMessage={true}
          />
        </div>
      </main>
    </>
  )
}
