'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Search, Plus, Edit, Trash2, Eye, EyeOff } from 'lucide-react'
import { isAuthenticated } from '@/lib/auth'
import { apiGet, apiDelete, apiPut } from '@/lib/apiClient'
import LoadingSpinner from '@/components/LoadingSpinner'

interface Page {
  _id: string
  title: string
  slug: string
  excerpt?: string
  content: string
  isPublished: boolean
  createdAt: string
}

export default function PagesPage() {
  const router = useRouter()
  const [pages, setPages] = useState<Page[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [filterStatus, setFilterStatus] = useState('all')

  useEffect(() => {
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    fetchPages()
  }, [router])

  const fetchPages = async () => {
    try {
      const result = await apiGet<Page[]>('/pages')
      if (result.success !== false && result.data) {
        setPages(result.data)
      } else if (Array.isArray(result)) {
        // Handle case where API returns array directly
        setPages(result)
      }
    } catch (error: any) {
      console.error('Error fetching pages:', error)
      if (error.message?.includes('Authentication required')) {
        router.push('/admin')
      }
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this page?')) return

    try {
      const result = await apiDelete(`/pages/${id}`)
      if (result.success !== false) {
        fetchPages()
      }
    } catch (error: any) {
      console.error('Error deleting page:', error)
      alert(error.message || 'Failed to delete page')
    }
  }

  const togglePublish = async (id: string, currentStatus: boolean) => {
    try {
      const result = await apiPut(`/pages/${id}`, {
        isPublished: !currentStatus
      })
      if (result.success !== false) {
        fetchPages()
      }
    } catch (error: any) {
      console.error('Error toggling publish status:', error)
      alert(error.message || 'Failed to update publish status')
    }
  }

  const filteredPages = pages.filter(page => {
    const matchesSearch = 
      page.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      page.slug.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (page.excerpt && page.excerpt.toLowerCase().includes(searchTerm.toLowerCase()))
    const matchesStatus = filterStatus === 'all' || 
      (filterStatus === 'published' ? page.isPublished : !page.isPublished)
    return matchesSearch && matchesStatus
  })

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <LoadingSpinner />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-white mb-2">Pages</h1>
          <p className="text-white/70">Manage website pages</p>
        </div>
        <button
          onClick={() => router.push('/admin/pages/new')}
          className="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg transition-all"
        >
          <Plus className="w-5 h-5" />
          New Page
        </button>
      </div>

      {/* Filters */}
      <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="md:col-span-2 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-white/50" />
            <input
              type="text"
              placeholder="Search pages..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>

          <div>
            <select
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value)}
              className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary appearance-none"
            >
              <option value="all">All Status</option>
              <option value="published">Published</option>
              <option value="draft">Draft</option>
            </select>
          </div>
        </div>
      </div>

      {/* Pages Table */}
      <div className="bg-white/10 backdrop-blur-xl rounded-xl border border-white/20 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-white/5 border-b border-white/10">
              <tr>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Title</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Slug</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Status</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Created</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/10">
              {filteredPages.map((page) => (
                <tr key={page._id} className="hover:bg-white/5 transition-colors">
                  <td className="px-6 py-4">
                    <div>
                      <p className="text-white font-medium">{page.title}</p>
                      {page.excerpt && (
                        <p className="text-white/50 text-sm line-clamp-1">{page.excerpt}</p>
                      )}
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <code className="text-primary text-sm">/{page.slug}</code>
                  </td>
                  <td className="px-6 py-4">
                    <span className={`px-3 py-1 rounded-full text-xs font-medium ${
                      page.isPublished 
                        ? 'bg-green-500/20 text-green-400' 
                        : 'bg-gray-500/20 text-gray-400'
                    }`}>
                      {page.isPublished ? 'Published' : 'Draft'}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-white/70 text-sm">
                    {new Date(page.createdAt).toLocaleDateString()}
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() => router.push(`/admin/pages/${page._id}`)}
                        className="p-2 text-blue-400 hover:bg-blue-500/20 rounded-lg transition-all"
                        title="Edit"
                      >
                        <Edit className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => togglePublish(page._id, page.isPublished)}
                        className="p-2 text-yellow-400 hover:bg-yellow-500/20 rounded-lg transition-all"
                        title={page.isPublished ? 'Unpublish' : 'Publish'}
                      >
                        {page.isPublished ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                      </button>
                      <button
                        onClick={() => handleDelete(page._id)}
                        className="p-2 text-red-400 hover:bg-red-500/20 rounded-lg transition-all"
                        title="Delete"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {filteredPages.length === 0 && (
          <div className="p-12 text-center">
            <p className="text-white/50">No pages found</p>
          </div>
        )}
      </div>
    </div>
  )
}
