import { useState, useEffect, useCallback } from 'react'
import { Plus, Trash2, Pencil, FolderTree } from 'lucide-react'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
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 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 },
        ]} />
      ),
    },
  ]

  return (
    <div className="space-y-6">
      <PageHeader
        title="Global Categories"
        description="Manage tree categories available to all accounts"
        action={
          <Button onClick={() => setCreateOpen(true)}>
            <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 variant="secondary" onClick={() => setCreateOpen(false)}>Cancel</Button>
            <Button onClick={handleCreate} disabled={!form.name || !form.slug}>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" />
          </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" />
          </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" />
          </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 variant="secondary" onClick={() => setEditCategory(null)}>Cancel</Button>
            <Button onClick={handleUpdate} disabled={!form.name || !form.slug}>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" />
          </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" />
          </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" />
          </div>
        </div>
      </Modal>
    </div>
  )
}

export default GlobalCategoriesPage
