'use client'

import { useState, useEffect, useCallback } from 'react'
import { useTranslations } from 'next-intl'
import { Header } from '@/components/layout/Header'
import { PlazaFilters } from './PlazaFilters'
import { PromptCard } from './PromptCard'
import { Button } from '@/components/ui/button'
import { Loader2 } from 'lucide-react'

interface Prompt {
  id: string
  name: string
  content: string
  description: string | null
  createdAt: string
  user: {
    id: string
    username: string | null
    avatar: string | null
  }
  tags: Array<{
    id: string
    name: string
    color: string
  }>
  versions: Array<{
    content: string
    version: number
    createdAt: string
  }>
  stats?: {
    viewCount: number
    likeCount: number
    rating: number | null
    ratingCount: number
  } | null
  _count: {
    versions: number
  }
}

interface PlazaResponse {
  prompts: Prompt[]
  pagination: {
    page: number
    limit: number
    total: number
    totalPages: number
    hasNext: boolean
    hasPrev: boolean
  }
}

interface Tag {
  id: string
  name: string
  color: string
  _count: {
    prompts: number
  }
}

export function PlazaClient() {
  const t = useTranslations('plaza')
  const [prompts, setPrompts] = useState<Prompt[]>([])
  const [tags, setTags] = useState<Tag[]>([])
  const [loading, setLoading] = useState(true)
  const [loadingMore, setLoadingMore] = useState(false)
  const [search, setSearch] = useState('')
  const [selectedTag, setSelectedTag] = useState('')
  const [sortBy, setSortBy] = useState('createdAt')
  const [sortOrder, setSortOrder] = useState('desc')
  const [pagination, setPagination] = useState({
    page: 1,
    limit: 12,
    total: 0,
    totalPages: 0,
    hasNext: false,
    hasPrev: false,
  })

  const fetchPrompts = useCallback(async (page = 1, reset = false) => {
    if (page === 1) setLoading(true)
    else setLoadingMore(true)

    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: pagination.limit.toString(),
        sortBy,
        sortOrder,
      })

      if (search) params.append('search', search)
      if (selectedTag) params.append('tag', selectedTag)

      const response = await fetch(`/api/plaza?${params}`)
      if (!response.ok) throw new Error('Failed to fetch')

      const data: PlazaResponse = await response.json()
      
      if (reset) {
        setPrompts(data.prompts)
      } else {
        setPrompts(prev => [...prev, ...data.prompts])
      }
      
      setPagination(data.pagination)
    } catch (error) {
      console.error('Error fetching prompts:', error)
    } finally {
      setLoading(false)
      setLoadingMore(false)
    }
  }, [search, selectedTag, sortBy, sortOrder, pagination.limit])

  const fetchTags = useCallback(async () => {
    try {
      const response = await fetch('/api/plaza/tags')
      if (!response.ok) throw new Error('Failed to fetch tags')
      
      const data = await response.json()
      setTags(data.tags)
    } catch (error) {
      console.error('Error fetching tags:', error)
    }
  }, [])

  useEffect(() => {
    fetchTags()
  }, [fetchTags])

  useEffect(() => {
    fetchPrompts(1, true)
  }, [search, selectedTag, sortBy, sortOrder, fetchPrompts])

  const handleLoadMore = () => {
    if (pagination.hasNext && !loadingMore) {
      fetchPrompts(pagination.page + 1, false)
    }
  }

  const handleClearFilters = () => {
    setSearch('')
    setSelectedTag('')
    setSortBy('createdAt')
    setSortOrder('desc')
  }

  const incrementViewCount = async (promptId: string) => {
    try {
      await fetch(`/api/plaza/${promptId}/view`, {
        method: 'POST',
      })
    } catch (error) {
      console.error('Error updating view count:', error)
    }
  }

  return (
    <div className="min-h-screen bg-background">
      <Header />
      
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Header */}
        <div className="text-center mb-8">
          <h1 className="text-4xl font-bold text-foreground mb-4">
            {t('title')}
          </h1>
          <p className="text-lg text-muted-foreground max-w-2xl mx-auto">
            {t('subtitle')}
          </p>
        </div>

        {/* Filters */}
        <PlazaFilters
          search={search}
          onSearchChange={setSearch}
          selectedTag={selectedTag}
          onTagChange={setSelectedTag}
          tags={tags}
          sortBy={sortBy}
          onSortByChange={setSortBy}
          sortOrder={sortOrder}
          onSortOrderChange={setSortOrder}
          onClearFilters={handleClearFilters}
        />

        {/* Results */}
        <div className="mb-6">
          <p className="text-sm text-muted-foreground">
            {t('showingResults', {
              current: prompts.length,
              total: pagination.total
            })}
          </p>
        </div>

        {/* Content */}
        {loading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin" />
            <span className="ml-2">{t('loadingPrompts')}</span>
          </div>
        ) : prompts.length > 0 ? (
          <>
            {/* Prompt Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
              {prompts.map((prompt) => (
                <PromptCard
                  key={prompt.id}
                  prompt={prompt}
                  onViewIncrement={incrementViewCount}
                />
              ))}
            </div>

            {/* Load More */}
            {pagination.hasNext && (
              <div className="text-center">
                <Button
                  onClick={handleLoadMore}
                  disabled={loadingMore}
                  variant="outline"
                  size="lg"
                >
                  {loadingMore ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin mr-2" />
                      {t('loadingPrompts')}
                    </>
                  ) : (
                    t('loadMore')
                  )}
                </Button>
              </div>
            )}
          </>
        ) : (
          <div className="text-center py-12">
            <h3 className="text-lg font-medium text-foreground mb-2">
              {t('noPromptsFound')}
            </h3>
            <p className="text-muted-foreground mb-4">
              {t('noPromptsMessage')}
            </p>
            <Button variant="outline" onClick={handleClearFilters}>
              {t('clearFilters')}
            </Button>
          </div>
        )}
      </main>
    </div>
  )
}