'use client'

import { useEffect, useState } from 'react'
import { Plus, Pencil, Trash2, Loader2, X, Eye, EyeOff, ExternalLink } from 'lucide-react'
import toast from 'react-hot-toast'

interface CmsPage {
  id: string
  slug: string
  title: string
  content: string
  isPublished: boolean
  createdAt: string
  updatedAt: string
}

const defaultForm = {
  slug: '',
  title: '',
  content: '',
}

export default function CmsManagementPage() {
  const [pages, setPages] = useState<CmsPage[]>([])
  const [loading, setLoading] = useState(true)
  const [showModal, setShowModal] = useState(false)
  const [editing, setEditing] = useState<CmsPage | null>(null)
  const [form, setForm] = useState(defaultForm)
  const [saving, setSaving] = useState(false)

  const fetchPages = async () => {
    try {
      const res = await fetch('/api/superadmin/cms')
      const data = await res.json()
      setPages(data.pages || [])
    } catch {
      toast.error('Gagal memuat halaman')
    } finally {
      setLoading(false)
    }
  }

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

  const openCreate = () => {
    setEditing(null)
    setForm(defaultForm)
    setShowModal(true)
  }

  const openEdit = (page: CmsPage) => {
    setEditing(page)
    setForm({
      slug: page.slug,
      title: page.title,
      content: page.content,
    })
    setShowModal(true)
  }

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault()
    setSaving(true)
    try {
      if (editing) {
        const res = await fetch(`/api/superadmin/cms/${editing.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ title: form.title, content: form.content }),
        })
        if (!res.ok) {
          const data = await res.json()
          throw new Error(data.error)
        }
        toast.success('Halaman berhasil diupdate')
      } else {
        const res = await fetch('/api/superadmin/cms', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(form),
        })
        if (!res.ok) {
          const data = await res.json()
          throw new Error(data.error)
        }
        toast.success('Halaman berhasil ditambahkan')
      }
      setShowModal(false)
      setEditing(null)
      setForm(defaultForm)
      fetchPages()
    } catch (err: any) {
      toast.error(err.message || 'Gagal menyimpan halaman')
    } finally {
      setSaving(false)
    }
  }

  const handleTogglePublish = async (page: CmsPage) => {
    try {
      const res = await fetch(`/api/superadmin/cms/${page.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ isPublished: !page.isPublished }),
      })
      if (!res.ok) throw new Error('Gagal mengubah status')
      toast.success(page.isPublished ? 'Halaman di-unpublish' : 'Halaman dipublish')
      fetchPages()
    } catch (err: any) {
      toast.error(err.message)
    }
  }

  const handleDelete = async (page: CmsPage) => {
    if (!confirm(`Hapus halaman "${page.title}"? Aksi ini tidak bisa dibatalkan.`)) return
    try {
      const res = await fetch(`/api/superadmin/cms/${page.id}`, { method: 'DELETE' })
      if (!res.ok) throw new Error('Gagal menghapus')
      toast.success('Halaman dihapus')
      fetchPages()
    } catch (err: any) {
      toast.error(err.message)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
      </div>
    )
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Halaman CMS</h1>
          <p className="text-gray-600 mt-1">Kelola halaman statis seperti Kebijakan Privasi, Syarat & Ketentuan, dll.</p>
        </div>
        <button onClick={openCreate} className="btn-primary text-sm flex items-center gap-1">
          <Plus className="w-4 h-4" /> Tambah Halaman
        </button>
      </div>

      <div className="card">
        {pages.length === 0 ? (
          <p className="text-gray-500 text-center py-8">Belum ada halaman CMS</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-gray-50">
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Judul</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Slug</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Status</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Terakhir Diubah</th>
                  <th className="text-left py-3 px-3 font-medium text-gray-600">Aksi</th>
                </tr>
              </thead>
              <tbody>
                {pages.map((page) => (
                  <tr key={page.id} className="border-b border-gray-100 hover:bg-gray-50">
                    <td className="py-3 px-3 font-medium text-gray-900">{page.title}</td>
                    <td className="py-3 px-3">
                      <a
                        href={`/p/${page.slug}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-indigo-600 hover:underline inline-flex items-center gap-1"
                      >
                        /p/{page.slug} <ExternalLink className="w-3 h-3" />
                      </a>
                    </td>
                    <td className="py-3 px-3">
                      <span className={`badge ${page.isPublished ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}`}>
                        {page.isPublished ? 'Published' : 'Draft'}
                      </span>
                    </td>
                    <td className="py-3 px-3 text-gray-500">
                      {new Date(page.updatedAt).toLocaleDateString('id-ID', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })}
                    </td>
                    <td className="py-3 px-3">
                      <div className="flex items-center gap-1">
                        <button
                          onClick={() => handleTogglePublish(page)}
                          className="btn-ghost text-xs p-1.5"
                          title={page.isPublished ? 'Unpublish' : 'Publish'}
                        >
                          {page.isPublished ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                        </button>
                        <button onClick={() => openEdit(page)} className="btn-ghost text-xs p-1.5">
                          <Pencil className="w-4 h-4" />
                        </button>
                        <button onClick={() => handleDelete(page)} className="btn-ghost text-xs p-1.5 text-red-500 hover:bg-red-50">
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Create/Edit Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="bg-white rounded-xl w-full max-w-2xl p-6 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold">{editing ? 'Edit Halaman' : 'Tambah Halaman'}</h3>
              <button onClick={() => setShowModal(false)}>
                <X className="w-5 h-5 text-gray-400" />
              </button>
            </div>
            <form onSubmit={handleSave} className="space-y-4">
              {!editing && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Slug (URL)</label>
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-gray-500">/p/</span>
                    <input
                      type="text"
                      className="input-field flex-1"
                      value={form.slug}
                      onChange={(e) => setForm({ ...form, slug: e.target.value })}
                      placeholder="contoh: privacy-policy"
                      required
                    />
                  </div>
                  <p className="text-xs text-gray-500 mt-1">Hanya huruf kecil, angka, dan tanda hubung (-)</p>
                </div>
              )}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Judul</label>
                <input
                  type="text"
                  className="input-field"
                  value={form.title}
                  onChange={(e) => setForm({ ...form, title: e.target.value })}
                  placeholder="Judul halaman"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Konten (HTML)</label>
                <textarea
                  className="input-field font-mono text-sm"
                  rows={15}
                  value={form.content}
                  onChange={(e) => setForm({ ...form, content: e.target.value })}
                  placeholder="<h2>Sub Judul</h2><p>Konten halaman...</p>"
                />
                <p className="text-xs text-gray-500 mt-1">Gunakan tag HTML untuk formatting (h2, h3, p, ul, ol, li, strong, em, a)</p>
              </div>
              <div className="flex gap-2 justify-end pt-2">
                <button type="button" onClick={() => setShowModal(false)} className="btn-secondary">
                  Batal
                </button>
                <button type="submit" disabled={saving} className="btn-primary flex items-center gap-2">
                  {saving && <Loader2 className="w-4 h-4 animate-spin" />}
                  {saving ? 'Menyimpan...' : 'Simpan'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  )
}
