import { useState, useEffect, useCallback } from 'react'
import { Plus, Trash2, Pencil, FolderTree } from 'lucide-react'
import { DataTable, PageHeader, ActionMenu, EmptyState } from '@/components/admin'
import type { Column } from '@/components/admin'
import { Modal } from '@/components/common/Modal'
import { adminApi } from '@/api/admin'
import { toast } from '@/lib/toast'
import { cn } from '@/lib/utils'
import type { AdminCategory, GlobalCategoryCreate } from '@/types/admin'

export function GlobalCategoriesPage() {
  const [categories, setCategories] = useState<AdminCategory[]>([])
  const [loading, setLoading] = useState(true)
  const [createOpen, setCreateOpen] = useState(false)
  const [editCategory, setEditCategory] = useState<AdminCategory | null>(null)
  const [form, setForm] = useState<GlobalCategoryCreate>({ name: '', slug: '', description: '' })

  const fetchData = useCallback(async () => {
    setLoading(true)
    try {
      setCategories(await adminApi.listGlobalCategories())
    } catch {
      toast.error('Failed to load categories')
    } finally {
      setLoading(false)
    }
  }, [])

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

  const generateSlug = (name: string) =>
    name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')

  const handleCreate = async () => {
    try {
      await adminApi.createGlobalCategory(form)
      toast.success('Category created')
      setCreateOpen(false)
      setForm({ name: '', slug: '', description: '' })
      fetchData()
    } catch {
      toast.error('Failed to create category')
    }
  }

  const handleUpdate = async () => {
    if (!editCategory) return
    try {
      await adminApi.updateGlobalCategory(editCategory.id, form)
      toast.success('Category updated')
      setEditCategory(null)
      setForm({ name: '', slug: '', description: '' })
      fetchData()
    } catch {
      toast.error('Failed to update category')
    }
  }

  const handleDelete = async (id: string) => {
    try {
      await adminApi.deleteGlobalCategory(id)
      toast.success('Category deleted')
      fetchData()
    } catch {
      toast.error('Failed to delete category')
    }
  }

  const openEdit = (cat: AdminCategory) => {
    setEditCategory(cat)
    setForm({ name: cat.name, slug: cat.slug, description: cat.description || '' })
  }

  const columns: Column<AdminCategory>[] = [
    { key: 'name', header: 'Name', render: (c) => <span className="font-medium text-foreground">{c.name}</span> },
    { key: 'slug', header: 'Slug', render: (c) => <span className="text-sm text-muted-foreground">{c.slug}</span> },
    { key: 'description', header: 'Description', render: (c) => <span className="text-sm text-muted-foreground">{c.description || '-'}</span> },
    { key: 'tree_count', header: 'Trees', render: (c) => <span className="text-sm text-muted-foreground">{c.tree_count}</span> },
    {
      key: 'actions', header: '', className: 'w-12',
      render: (c) => (
        <ActionMenu items={[
          { label: 'Edit', icon: <Pencil className="h-4 w-4" />, onClick: () => openEdit(c) },
          { label: 'Delete', icon: <Trash2 className="h-4 w-4" />, onClick: () => handleDelete(c.id), destructive: true },
        ]} />
      ),
    },
  ]

  const inputCn = cn('w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground', 'placeholder:text-muted-foreground focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20')

  return (
    <div className="space-y-6">
      <PageHeader
        title="Global Categories"
        description="Manage tree categories available to all accounts"
        action={
          <button onClick={() => setCreateOpen(true)} className={cn('flex items-center gap-2 rounded-md px-4 py-2 text-sm font-medium', 'bg-gradient-brand text-white shadow-lg shadow-primary/20 hover:opacity-90')}>
            <Plus className="h-4 w-4" />
            Create Category
          </button>
        }
      />

      <DataTable
        columns={columns}
        data={categories}
        keyExtractor={(c) => c.id}
        isLoading={loading}
        emptyState={<EmptyState icon={<FolderTree className="h-12 w-12" />} title="No global categories" description="Create categories to help organize trees across the platform." />}
      />

      {/* Create Modal */}
      <Modal
        isOpen={createOpen}
        onClose={() => { setCreateOpen(false); setForm({ name: '', slug: '', description: '' }) }}
        title="Create Category"
        size="sm"
        footer={
          <div className="flex justify-end gap-3">
            <button onClick={() => setCreateOpen(false)} className="rounded-md border border-border px-4 py-2 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-foreground">Cancel</button>
            <button onClick={handleCreate} disabled={!form.name || !form.slug} className="rounded-md bg-gradient-brand text-white shadow-lg shadow-primary/20 px-4 py-2 text-sm font-medium hover:opacity-90 disabled:opacity-50">Create</button>
          </div>
        }
      >
        <div className="space-y-4">
          <div>
            <label className="mb-1 block text-sm font-medium text-foreground">Name</label>
            <input type="text" value={form.name} onChange={(e) => { const name = e.target.value; setForm(f => ({ ...f, name, slug: generateSlug(name) })) }} placeholder="e.g. Networking" className={inputCn} />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-foreground">Slug</label>
            <input type="text" value={form.slug} onChange={(e) => setForm({ ...form, slug: e.target.value })} placeholder="e.g. networking" className={inputCn} />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-foreground">Description</label>
            <input type="text" value={form.description ?? ''} onChange={(e) => setForm({ ...form, description: e.target.value || null })} placeholder="Optional description" className={inputCn} />
          </div>
        </div>
      </Modal>

      {/* Edit Modal */}
      <Modal
        isOpen={!!editCategory}
        onClose={() => { setEditCategory(null); setForm({ name: '', slug: '', description: '' }) }}
        title="Edit Category"
        size="sm"
        footer={
          <div className="flex justify-end gap-3">
            <button onClick={() => setEditCategory(null)} className="rounded-md border border-border px-4 py-2 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-foreground">Cancel</button>
            <button onClick={handleUpdate} disabled={!form.name || !form.slug} className="rounded-md bg-gradient-brand text-white shadow-lg shadow-primary/20 px-4 py-2 text-sm font-medium hover:opacity-90 disabled:opacity-50">Save</button>
          </div>
        }
      >
        <div className="space-y-4">
          <div>
            <label className="mb-1 block text-sm font-medium text-foreground">Name</label>
            <input type="text" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="e.g. Networking" className={inputCn} />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-foreground">Slug</label>
            <input type="text" value={form.slug} onChange={(e) => setForm({ ...form, slug: e.target.value })} placeholder="e.g. networking" className={inputCn} />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-foreground">Description</label>
            <input type="text" value={form.description ?? ''} onChange={(e) => setForm({ ...form, description: e.target.value || null })} placeholder="Optional description" className={inputCn} />
          </div>
        </div>
      </Modal>
    </div>
  )
}

export default GlobalCategoriesPage
