import React from 'react'
import { Head, Link, router, usePage } from '@inertiajs/react'
import AdminLayout from '../../../Layouts/AdminLayout'

export default function AcademyCrudIndex({ title, subtitle, items, columns, createUrl }) {
  const flash = usePage().props.flash || {}

  return (
    <AdminLayout title={title} subtitle={subtitle}>
      <Head title={`Admin · ${title}`} />

      {flash.success ? <div className="mb-6 rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100">{flash.success}</div> : null}

      <div className="mb-6 flex items-center justify-between gap-4">
        <p className="text-sm text-slate-400">Manage Academy content below. Changes clear Academy cache automatically.</p>
        <Link href={createUrl} className="rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100">Create record</Link>
      </div>

      {(items?.data || []).length === 0 ? (
        <div className="rounded-[28px] border border-white/[0.08] bg-white/[0.03] px-6 py-12 text-center text-slate-400">No records exist yet.</div>
      ) : (
        <div className="space-y-4">
          {items.data.map((item) => (
            <div key={item.id} className="rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-5">
              <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-center">
                <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-5">
                  {columns.map((column) => (
                    <div key={column}>
                      <p className="text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500">{column.replaceAll('_', ' ')}</p>
                      <p className="mt-1 text-sm text-white">{String(item[column] ?? '')}</p>
                    </div>
                  ))}
                </div>

                <div className="flex flex-wrap gap-3 lg:justify-end">
                  <Link href={item.edit_url} className="rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white">Edit</Link>
                  <button type="button" onClick={() => { if (!window.confirm('Delete this record?')) return; router.delete(item.destroy_url, { preserveScroll: true }) }} className="rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm font-semibold text-rose-100">Delete</button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </AdminLayout>
  )
}