'use client'

import { useEffect, useState, useCallback } from 'react'
import { useTranslations } from 'next-intl'
import { useAuth } from '@/hooks/useAuth'
import { useRouter } from 'next/navigation'
import { Header } from '@/components/layout/Header'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { LoadingRing } from '@/components/ui/loading-ring'
import { EditPromptModal } from '@/components/studio/EditPromptModal'
import { PromptDetailModal } from '@/components/studio/PromptDetailModal'
import { BulkAddPromptModal } from '@/components/studio/BulkAddPromptModal'
import { PermissionToggle } from '@/components/studio/PermissionToggle'
import {
  Plus,
  Search,
  Edit,
  Play,
  FileText,
  Calendar,
  ChevronDown,
  Grid,
  List,
  FolderPlus
} from 'lucide-react'

interface Prompt {
  id: string
  name: string
  description: string | null
  content: string
  tags: string[]
  createdAt: string
  updatedAt: string
  lastUsed?: string | null
  currentVersion?: number
  usage?: number
  permissions?: 'private' | 'public'
  visibility?: 'under_review' | 'published' | null
}

interface PaginationInfo {
  page: number
  limit: number
  total: number
  totalPages: number
}

type SortField = 'name' | 'createdAt' | 'updatedAt' | 'lastUsed'
type SortOrder = 'asc' | 'desc'
type ViewMode = 'grid' | 'list'

export default function StudioPage() {
  const { user, loading } = useAuth()
  const router = useRouter()
  const t = useTranslations('studio')

  const [prompts, setPrompts] = useState<Prompt[]>([])
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedTag, setSelectedTag] = useState<string>('')
  const [sortField, setSortField] = useState<SortField>('updatedAt')
  const [sortOrder, setSortOrder] = useState<SortOrder>('desc')
  const [viewMode, setViewMode] = useState<ViewMode>('grid')
  const [isLoading, setIsLoading] = useState(false)
  const [isInitialLoad, setIsInitialLoad] = useState(true)
  const [allTags, setAllTags] = useState<string[]>([])

  // Edit Modal
  const [editingPrompt, setEditingPrompt] = useState<Prompt | null>(null)
  const [isEditModalOpen, setIsEditModalOpen] = useState(false)

  // Detail Modal
  const [detailPrompt, setDetailPrompt] = useState<Prompt | null>(null)
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false)

  // Bulk Add Modal
  const [isBulkAddModalOpen, setIsBulkAddModalOpen] = useState(false)

  // Pagination
  const [currentPage, setCurrentPage] = useState(1)
  const itemsPerPage = 12
  const [pagination, setPagination] = useState<PaginationInfo>({
    page: 1,
    limit: 12,
    total: 0,
    totalPages: 0
  })

  // Fetch prompts from API
  const fetchPrompts = useCallback(async (showLoading = false) => {
    if (!user) return

    try {
      if (showLoading) {
        setIsLoading(true)
      }
      const params = new URLSearchParams({
        userId: user.id,
        page: currentPage.toString(),
        limit: itemsPerPage.toString(),
        search: searchQuery,
        tag: selectedTag,
        sortBy: sortField,
        sortOrder: sortOrder
      })

      const response = await fetch(`/api/prompts?${params}`)
      if (response.ok) {
        const data = await response.json()
        setPrompts(data.prompts)
        setPagination(data.pagination)
      }
    } catch (error) {
      console.error('Error fetching prompts:', error)
    } finally {
      if (showLoading) {
        setIsLoading(false)
      }
      if (isInitialLoad) {
        setIsInitialLoad(false)
      }
    }
  }, [user, currentPage, itemsPerPage, searchQuery, selectedTag, sortField, sortOrder, isInitialLoad])

  // Initialize and fetch tags only once
  useEffect(() => {
    if (!loading && !user) {
      router.push('/signin')
      return
    }

    if (!user) return

    const fetchTags = async () => {
      try {
        const response = await fetch(`/api/tags?userId=${user.id}`)
        if (response.ok) {
          const tags = await response.json()
          setAllTags(tags.map((tag: { name: string }) => tag.name))
        }
      } catch (error) {
        console.error('Error fetching tags:', error)
      }
    }

    fetchTags()
  }, [user, loading, router])

  // Fetch prompts with debounced search
  useEffect(() => {
    if (!user) return

    const timeoutId = setTimeout(() => {
      fetchPrompts(isInitialLoad)
    }, searchQuery ? 300 : 0) // Debounce search queries

    return () => clearTimeout(timeoutId)
  }, [currentPage, searchQuery, selectedTag, sortField, sortOrder, user, fetchPrompts, isInitialLoad])

  // Since filtering and sorting is now done on the server,
  // we use prompts directly without additional state

  const handleCreatePrompt = () => {
    router.push('/studio/new')
  }

  const handleEditPrompt = (id: string) => {
    router.push(`/studio/${id}`)
  }

  const handleQuickEdit = (prompt: Prompt) => {
    setEditingPrompt(prompt)
    setIsEditModalOpen(true)
  }

  const handleEditModalClose = () => {
    setIsEditModalOpen(false)
    setEditingPrompt(null)
  }

  const handleEditModalSave = (updatedPrompt: Prompt) => {
    // Update the prompt in the local state
    setPrompts(prev => prev.map(p => p.id === updatedPrompt.id ? updatedPrompt : p))
  }

  const handleShowDetails = (prompt: Prompt) => {
    setDetailPrompt(prompt)
    setIsDetailModalOpen(true)
  }

  const handleDetailModalClose = () => {
    setIsDetailModalOpen(false)
    setDetailPrompt(null)
  }

  const handleDebugPrompt = (id: string) => {
    router.push(`/studio/${id}`)
  }

  const handleUpdatePermissions = async (promptId: string, newPermissions: 'private' | 'public') => {
    if (!user) return

    try {
      const response = await fetch(`/api/prompts/${promptId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          permissions: newPermissions,
          userId: user.id
        })
      })

      if (!response.ok) {
        throw new Error('Failed to update permissions')
      }

      // Update the prompt in local state
      const updatedPrompt = await response.json()
      setPrompts(prev => prev.map(p => p.id === promptId ? { ...p, permissions: updatedPrompt.permissions, visibility: updatedPrompt.visibility } : p))
    } catch (error) {
      console.error('Error updating permissions:', error)
      throw error
    }
  }

  const handleBulkAdd = async (bulkPrompts: Array<{
    id: string
    name: string
    description: string
    tags: string
    content: string
  }>) => {
    try {
      // Process each prompt
      const promptsToCreate = bulkPrompts.map(bulkPrompt => ({
        name: bulkPrompt.name.trim(),
        description: bulkPrompt.description.trim() || null,
        content: bulkPrompt.content.trim(),
        tags: bulkPrompt.tags
          .split(',')
          .map(tag => tag.trim())
          .filter(tag => tag.length > 0),
        userId: user?.id || ''
      }))

      // Use the bulk create API endpoint
      const response = await fetch('/api/prompts/bulk', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompts: promptsToCreate })
      })

      if (!response.ok) {
        throw new Error('Failed to create prompts')
      }

      // Refresh the prompts list
      await fetchPrompts(false)
      setIsBulkAddModalOpen(false)
    } catch (error) {
      console.error('Error bulk adding prompts:', error)
      throw error
    }
  }



  const formatDate = (dateString: string) => {
    return new Intl.DateTimeFormat('default', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    }).format(new Date(dateString))
  }

  // Use server-side pagination
  const currentPrompts = prompts

  if (loading) {
    return null
  }

  if (!user) {
    return null
  }

  return (
    <div className="min-h-screen">
      <Header />

      <div className="max-w-7xl mx-auto px-4 py-8">
        {/* Header */}
        <div className="mb-8">
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-4">
            <div className="flex-1">
              <h1 className="text-2xl sm:text-3xl font-bold text-foreground">{t('title')}</h1>
              <p className="text-muted-foreground mt-1">{t('myPrompts')}</p>
            </div>
            <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3">
              <Button
                variant="outline"
                onClick={() => setIsBulkAddModalOpen(true)}
                className="flex items-center justify-center space-x-2 h-10"
              >
                <FolderPlus className="h-4 w-4" />
                <span className="hidden sm:inline">Bulk Add</span>
                <span className="sm:hidden">Bulk</span>
              </Button>
              <Button onClick={handleCreatePrompt} className="flex items-center justify-center space-x-2 h-10">
                <Plus className="h-4 w-4" />
                <span>{t('createPrompt')}</span>
              </Button>
            </div>
          </div>

          {/* Search and Filters */}
          <div className="bg-muted/30 rounded-xl p-3 sm:p-4 mb-6">
            <div className="space-y-3">
              {/* Search */}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder={t('searchPrompts')}
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-9 bg-background border-border/50 focus:border-primary transition-colors h-10"
                />
              </div>

              {/* Filters Row */}
              <div className="flex flex-wrap gap-2">
                {/* Tag Filter */}
                <div className="relative flex-1 min-w-[120px]">
                  <select
                    value={selectedTag}
                    onChange={(e) => setSelectedTag(e.target.value)}
                    className="appearance-none bg-background border border-border/50 rounded-lg px-3 py-2 pr-8 w-full focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-colors text-sm h-10"
                  >
                    <option value="">{t('allTags')}</option>
                    {allTags.map(tag => (
                      <option key={tag} value={tag}>{tag}</option>
                    ))}
                  </select>
                  <ChevronDown className="absolute right-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
                </div>

                {/* Sort */}
                <div className="relative flex-1 min-w-[140px]">
                  <select
                    value={`${sortField}-${sortOrder}`}
                    onChange={(e) => {
                      const [field, order] = e.target.value.split('-')
                      setSortField(field as SortField)
                      setSortOrder(order as SortOrder)
                    }}
                    className="appearance-none bg-background border border-border/50 rounded-lg px-3 py-2 pr-8 w-full focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-colors text-sm h-10"
                  >
                    <option value="updatedAt-desc">Latest</option>
                    <option value="updatedAt-asc">Oldest</option>
                    <option value="name-asc">A-Z</option>
                    <option value="name-desc">Z-A</option>
                    <option value="createdAt-desc">Created Latest</option>
                    <option value="createdAt-asc">Created Oldest</option>
                  </select>
                  <ChevronDown className="absolute right-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
                </div>

                {/* View Mode Toggle */}
                <div className="flex items-center bg-background border border-border/50 rounded-lg overflow-hidden h-10">
                  <Button
                    variant={viewMode === 'grid' ? 'default' : 'ghost'}
                    size="sm"
                    onClick={() => setViewMode('grid')}
                    className="rounded-none border-r border-border/20 h-full px-3"
                    title="Grid View"
                  >
                    <Grid className="h-4 w-4" />
                  </Button>
                  <Button
                    variant={viewMode === 'list' ? 'default' : 'ghost'}
                    size="sm"
                    onClick={() => setViewMode('list')}
                    className="rounded-none h-full px-3"
                    title="List View"
                  >
                    <List className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </div>
            
            {/* Quick Stats */}
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mt-3 pt-3 border-t border-border/30">
              <div className="text-sm text-muted-foreground">
                {prompts.length > 0 ? (
                  <span>
                    <span className="hidden sm:inline">Showing </span><span className="font-medium text-foreground">{prompts.length}</span> of <span className="font-medium text-foreground">{pagination.total}</span> prompts
                  </span>
                ) : (
                  <span>No prompts found</span>
                )}
              </div>
              {searchQuery && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setSearchQuery('')}
                  className="text-xs text-muted-foreground hover:text-foreground self-start sm:self-auto"
                >
                  Clear search
                </Button>
              )}
            </div>
          </div>

        </div>

        {/* Content */}
        {isLoading ? (
          <div className="text-center py-16">
            <LoadingRing size="lg" className="mb-4" />
            <p className="text-muted-foreground">{t('loadingStudio')}</p>
          </div>
        ) : prompts.length === 0 ? (
          <div className="text-center py-16">
            <div className="bg-muted/30 rounded-full w-24 h-24 flex items-center justify-center mx-auto mb-6">
              <FileText className="h-12 w-12 text-muted-foreground" />
            </div>
            <h3 className="text-xl font-semibold text-foreground mb-3">{t('noPrompts')}</h3>
            <p className="text-muted-foreground mb-6 max-w-md mx-auto leading-relaxed">{t('createFirstPrompt')}</p>
            <Button onClick={handleCreatePrompt} size="lg" className="font-medium">
              <Plus className="h-4 w-4 mr-2" />
              {t('createPrompt')}
            </Button>
          </div>
        ) : (
          <>
            {/* Prompts Grid/List */}
            {viewMode === 'grid' ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 sm:gap-4 lg:gap-6 mb-8">
                {currentPrompts.map((prompt) => (
                  <div
                    key={prompt.id}
                    className="group bg-card rounded-xl border border-border hover:border-primary/20 hover:shadow-lg transition-all duration-200 cursor-pointer overflow-hidden flex flex-col h-full"
                    onClick={() => handleShowDetails(prompt)}
                  >
                    {/* Card Header */}
                    <div className="p-3 sm:p-4 pb-3 flex-1">
                      <div className="mb-3">
                        <h3 className="font-semibold text-foreground text-sm sm:text-base leading-tight mb-2 group-hover:text-primary transition-colors">
                          <span className="line-clamp-2 break-words" title={prompt.name}>
                            {prompt.name}
                          </span>
                        </h3>
                        <div className="h-8 sm:h-10 overflow-hidden">
                          <p className="text-xs text-muted-foreground leading-relaxed line-clamp-2">
                            {prompt.description || 'No description available'}
                          </p>
                        </div>
                      </div>

                      {/* Tags */}
                      <div className="flex flex-wrap gap-1 mb-3 min-h-[20px]">
                        {prompt.tags?.slice(0, 2).map((tag: string | { name: string }) => {
                          const tagName = typeof tag === 'string' ? tag : tag?.name || '';
                          const displayTag = tagName.length > 12 ? tagName.slice(0, 12) + '...' : tagName;
                          return (
                            <span
                              key={tagName}
                              className="inline-flex items-center px-2 py-0.5 text-xs font-medium bg-primary/5 text-primary/80 rounded-full border border-primary/10"
                              title={tagName}
                            >
                              {displayTag}
                            </span>
                          );
                        })}
                        {prompt.tags && prompt.tags.length > 2 && (
                          <span className="inline-flex items-center px-2 py-0.5 text-xs font-medium bg-muted text-muted-foreground rounded-full" title={`${prompt.tags.length - 2} more tags`}>
                            +{prompt.tags.length - 2}
                          </span>
                        )}
                        {(!prompt.tags || prompt.tags.length === 0) && (
                          <span className="text-xs text-muted-foreground/50 italic">No tags</span>
                        )}
                      </div>
                    </div>

                    {/* Card Footer */}
                    <div className="px-3 sm:px-4 pb-3 sm:pb-4">
                      {/* Metadata */}
                      <div className="flex items-center justify-between text-xs text-muted-foreground mb-3 pt-2 border-t border-border/50">
                        <div className="flex items-center space-x-1">
                          <Calendar className="h-3 w-3" />
                          <span>{formatDate(prompt.updatedAt)}</span>
                        </div>
                        <div className="flex items-center space-x-1">
                          {prompt.currentVersion && (
                            <span className="bg-muted px-1.5 py-0.5 rounded text-xs font-medium">
                              v{prompt.currentVersion}
                            </span>
                          )}
                          {prompt.usage !== undefined && (
                            <span className="text-muted-foreground/70">
                              {prompt.usage} uses
                            </span>
                          )}
                        </div>
                      </div>

                      {/* Permissions */}
                      <div className="mb-3" onClick={(e) => e.stopPropagation()}>
                        <PermissionToggle
                          permissions={prompt.permissions || 'private'}
                          visibility={prompt.visibility}
                          onUpdate={(newPermissions) => handleUpdatePermissions(prompt.id, newPermissions)}
                          size="sm"
                          variant="compact"
                          className="w-full justify-center"
                        />
                      </div>

                      {/* Action Buttons */}
                      <div className="flex items-center space-x-1 sm:space-x-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={(e) => {
                            e.stopPropagation()
                            handleDebugPrompt(prompt.id)
                          }}
                          className="flex-1 h-7 sm:h-8 text-xs font-medium hover:bg-primary hover:text-primary-foreground transition-colors"
                        >
                          <Play className="h-3 w-3 mr-1" />
                          <span className="hidden sm:inline">Open Studio</span>
                          <span className="sm:hidden">Open</span>
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={(e) => {
                            e.stopPropagation()
                            handleQuickEdit(prompt)
                          }}
                          className="h-7 sm:h-8 w-7 sm:w-8 p-0 hover:bg-muted transition-colors"
                          title="Quick Edit"
                        >
                          <Edit className="h-3 w-3" />
                        </Button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="space-y-3 mb-8">
                {/* List Header */}
                <div className="hidden md:flex items-center px-4 py-3 bg-muted/50 rounded-lg text-sm font-semibold text-muted-foreground border border-border/50">
                  <div className="flex-1 min-w-0">{t('promptName')}</div>
                  <div className="w-28 text-center hidden lg:block">{t('updatedAt')}</div>
                  <div className="w-24 text-center">{t('tags')}</div>
                  <div className="w-24 text-center">Privacy</div>
                  <div className="w-20 text-center">Actions</div>
                </div>

                {/* List Items */}
                {currentPrompts.map((prompt) => (
                  <div
                    key={prompt.id}
                    className="group flex flex-col md:flex-row md:items-center p-4 bg-card rounded-xl border border-border hover:border-primary/20 hover:shadow-md transition-all duration-200 cursor-pointer"
                    onClick={() => handleShowDetails(prompt)}
                  >
                    {/* Main Content */}
                    <div className="flex-1 min-w-0 mb-3 md:mb-0">
                      <div className="flex items-start justify-between mb-2">
                        <h3 className="font-semibold text-foreground text-sm leading-tight group-hover:text-primary transition-colors pr-2">
                          <span className="line-clamp-1 break-words" title={prompt.name}>
                            {prompt.name}
                          </span>
                        </h3>
                      </div>
                      <p className="text-xs text-muted-foreground line-clamp-2 leading-relaxed mb-2">
                        {prompt.description || 'No description available'}
                      </p>
                      
                      {/* Mobile metadata */}
                      <div className="flex items-center justify-between text-xs text-muted-foreground md:hidden">
                        <span>Updated {formatDate(prompt.updatedAt)}</span>
                        {prompt.currentVersion && (
                          <span className="bg-muted px-2 py-1 rounded text-xs font-medium">
                            v{prompt.currentVersion}
                          </span>
                        )}
                      </div>
                      
                      {/* Mobile tags */}
                      <div className="flex flex-wrap gap-1 mt-2 md:hidden">
                        {prompt.tags?.slice(0, 4).map((tag: string | { name: string }) => {
                          const tagName = typeof tag === 'string' ? tag : tag?.name || '';
                          const displayTag = tagName.length > 12 ? tagName.slice(0, 12) + '...' : tagName;
                          return (
                            <span
                              key={tagName}
                              className="inline-flex items-center px-2 py-0.5 text-xs font-medium bg-primary/10 text-primary rounded-full border border-primary/20"
                              title={tagName}
                            >
                              {displayTag}
                            </span>
                          );
                        })}
                        {prompt.tags && prompt.tags.length > 4 && (
                          <span className="inline-flex items-center px-2 py-0.5 text-xs font-medium bg-muted text-muted-foreground rounded-full" title={`${prompt.tags.length - 4} more tags`}>
                            +{prompt.tags.length - 4}
                          </span>
                        )}
                        {(!prompt.tags || prompt.tags.length === 0) && (
                          <span className="text-xs text-muted-foreground/50 italic">No tags</span>
                        )}
                      </div>
                    </div>

                    {/* Desktop metadata */}
                    <div className="hidden md:flex items-center space-x-4">
                      <div className="w-28 text-sm text-muted-foreground text-center hidden lg:block">
                        {formatDate(prompt.updatedAt)}
                      </div>
                      <div className="w-24 flex justify-center">
                        <div className="flex flex-wrap gap-1 items-center justify-center">
                          {prompt.tags?.slice(0, 1).map((tag: string | { name: string }) => {
                            const tagName = typeof tag === 'string' ? tag : tag?.name || '';
                            const displayTag = tagName.length > 6 ? tagName.slice(0, 6) + '...' : tagName;
                            return (
                              <span
                                key={tagName}
                                className="inline-flex items-center px-2 py-0.5 text-xs font-medium bg-primary/10 text-primary rounded-full border border-primary/20"
                                title={tagName}
                              >
                                {displayTag}
                              </span>
                            );
                          })}
                          {prompt.tags && prompt.tags.length > 1 && (
                            <span className="inline-flex items-center px-1.5 py-0.5 text-xs font-medium bg-muted text-muted-foreground rounded-full" title={`${prompt.tags.length - 1} more tags`}>
                              +{prompt.tags.length - 1}
                            </span>
                          )}
                          {(!prompt.tags || prompt.tags.length === 0) && (
                            <span className="text-xs text-muted-foreground/50 italic">-</span>
                          )}
                        </div>
                      </div>
                      <div className="w-24 flex justify-center" onClick={(e) => e.stopPropagation()}>
                        <PermissionToggle
                          permissions={prompt.permissions || 'private'}
                          visibility={prompt.visibility}
                          onUpdate={(newPermissions) => handleUpdatePermissions(prompt.id, newPermissions)}
                          size="sm"
                          variant="compact"
                        />
                      </div>
                    </div>

                    {/* Actions */}
                    <div className="flex items-center justify-end space-x-2 mt-3 md:mt-0 md:w-20 pt-3 md:pt-0 border-t border-border/50 md:border-t-0">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation()
                          handleQuickEdit(prompt)
                        }}
                        className="h-8 px-3 md:w-8 md:px-0 text-xs font-medium hover:bg-primary/10 hover:text-primary transition-colors"
                        title="Quick Edit"
                      >
                        <Edit className="h-3 w-3 md:mr-0 mr-1" />
                        <span className="md:hidden">Edit</span>
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation()
                          handleDebugPrompt(prompt.id)
                        }}
                        className="h-8 px-3 text-xs font-medium hover:bg-primary hover:text-primary-foreground transition-colors md:hidden"
                      >
                        <Play className="h-3 w-3 mr-1" />
                        Open
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* Pagination */}
            {pagination.totalPages > 1 && (
              <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-0">
                <div className="text-sm text-muted-foreground text-center sm:text-left">
                  Page {pagination.page} of {pagination.totalPages}
                  <span className="hidden sm:inline"> • Total {pagination.total}</span>
                </div>

                <div className="flex items-center justify-center space-x-1 sm:space-x-2">
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={pagination.page === 1}
                    onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                    className="h-8 px-2 sm:px-3"
                  >
                    <span className="hidden sm:inline">Previous</span>
                    <span className="sm:hidden">Prev</span>
                  </Button>

                  {/* Show fewer page numbers on mobile */}
                  {Array.from({ length: Math.min(3, pagination.totalPages) }, (_, i) => {
                    const page = i + 1
                    return (
                      <Button
                        key={page}
                        variant={pagination.page === page ? 'default' : 'outline'}
                        size="sm"
                        onClick={() => setCurrentPage(page)}
                        className="h-8 w-8 p-0"
                      >
                        {page}
                      </Button>
                    )
                  })}

                  <Button
                    variant="outline"
                    size="sm"
                    disabled={pagination.page === pagination.totalPages}
                    onClick={() => setCurrentPage(prev => Math.min(pagination.totalPages, prev + 1))}
                    className="h-8 px-2 sm:px-3"
                  >
                    <span className="hidden sm:inline">Next</span>
                    <span className="sm:hidden">Next</span>
                  </Button>
                </div>
              </div>
            )}
          </>
        )}
      </div>

      {/* Edit Modal */}
      {editingPrompt && (
        <EditPromptModal
          prompt={editingPrompt}
          isOpen={isEditModalOpen}
          onClose={handleEditModalClose}
          onSave={handleEditModalSave}
          userId={user?.id || ''}
        />
      )}

      {/* Detail Modal */}
      <PromptDetailModal
        prompt={detailPrompt}
        isOpen={isDetailModalOpen}
        onClose={handleDetailModalClose}
        onEdit={handleEditPrompt}
        onDebug={handleDebugPrompt}
      />

      {/* Bulk Add Modal */}
      <BulkAddPromptModal
        isOpen={isBulkAddModalOpen}
        onClose={() => setIsBulkAddModalOpen(false)}
        onSave={handleBulkAdd}
        userId={user?.id || ''}
      />
    </div>
  )
}