import React from 'react'
import { Head, Link, usePage } from '@inertiajs/react'

function requestJson(url, { method = 'GET', body } = {}) {
  return fetch(url, {
    method,
    credentials: 'same-origin',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
      'X-Requested-With': 'XMLHttpRequest',
    },
    body: body ? JSON.stringify(body) : undefined,
  }).then(async (response) => {
    const payload = await response.json().catch(() => ({}))
    if (!response.ok) throw new Error(payload?.message || 'Request failed')
    return payload
  })
}

export default function NovaCardsAssetPackAdmin() {
  const { props } = usePage()
  const [packs, setPacks] = React.useState(props.packs || [])
  const [selectedId, setSelectedId] = React.useState(null)
  const [form, setForm] = React.useState({ slug: '', name: '', description: '', type: 'asset', preview_image: '', manifest_json: {}, official: true, active: true, order_num: 0 })
  const endpoints = props.endpoints || {}

  function loadPack(pack) {
    setSelectedId(pack.id)
    setForm({
      slug: pack.slug,
      name: pack.name,
      description: pack.description || '',
      type: pack.type || 'asset',
      preview_image: pack.preview_image || '',
      manifest_json: pack.manifest_json || {},
      official: Boolean(pack.official),
      active: Boolean(pack.active),
      order_num: pack.order_num || 0,
    })
  }

  function resetForm() {
    setSelectedId(null)
    setForm({ slug: '', name: '', description: '', type: 'asset', preview_image: '', manifest_json: {}, official: true, active: true, order_num: packs.length })
  }

  async function savePack() {
    const isExisting = Boolean(selectedId)
    const url = isExisting ? String(endpoints.updatePattern || '').replace('__PACK__', String(selectedId)) : endpoints.store
    const response = await requestJson(url, { method: isExisting ? 'PATCH' : 'POST', body: form })
    if (isExisting) {
      setPacks((current) => current.map((pack) => (pack.id === selectedId ? response.pack : pack)))
    } else {
      setPacks((current) => [...current, response.pack])
      setSelectedId(response.pack.id)
    }
  }

  return (
    <div className="mx-auto max-w-7xl px-4 pb-20 pt-8 sm:px-6 lg:px-8">
      <Head title="Nova Cards Asset Packs" />

      <section className="rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.88))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
          <div>
            <p className="text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/75">V2 pack system</p>
            <h1 className="mt-3 text-3xl font-semibold tracking-[-0.04em] text-white">Official asset and template packs</h1>
            <p className="mt-3 max-w-3xl text-sm leading-7 text-slate-300">Control the official packs exposed in the v2 editor and public pack directories.</p>
          </div>
          <div className="flex gap-3">
            <button type="button" onClick={resetForm} className="rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]">New pack</button>
            <Link href={endpoints.cards || '/cp/cards'} className="rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]">Back to cards</Link>
          </div>
        </div>
      </section>

      <div className="mt-8 grid gap-6 xl:grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)]">
        <section className="rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]">
          <div className="mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400">Existing packs</div>
          <div className="space-y-3">
            {packs.map((pack) => (
              <button key={pack.id} type="button" onClick={() => loadPack(pack)} className={`w-full rounded-[22px] border p-4 text-left transition ${selectedId === pack.id ? 'border-sky-300/35 bg-sky-400/10' : 'border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.05]'}`}>
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="text-base font-semibold tracking-[-0.03em] text-white">{pack.name}</div>
                    <div className="mt-1 text-xs uppercase tracking-[0.18em] text-slate-500">{pack.slug}</div>
                  </div>
                  <span className="rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-200">{pack.type}</span>
                </div>
                {pack.description ? <div className="mt-2 text-sm text-slate-400">{pack.description}</div> : null}
              </button>
            ))}
          </div>
        </section>

        <section className="rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]">
          <div className="mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400">Pack editor</div>
          <div className="grid gap-4 md:grid-cols-2">
            <input value={form.name} onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))} placeholder="Pack name" className="rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" />
            <input value={form.slug} onChange={(event) => setForm((current) => ({ ...current, slug: event.target.value }))} placeholder="Slug" className="rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" />
            <textarea value={form.description} onChange={(event) => setForm((current) => ({ ...current, description: event.target.value }))} placeholder="Description" rows={3} className="rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white md:col-span-2" />
            <label className="text-sm text-slate-300">
              <span className="mb-2 block">Type</span>
              <select value={form.type} onChange={(event) => setForm((current) => ({ ...current, type: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white">
                <option value="asset">asset</option>
                <option value="template">template</option>
              </select>
            </label>
            <input value={form.preview_image} onChange={(event) => setForm((current) => ({ ...current, preview_image: event.target.value }))} placeholder="Preview image URL" className="rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" />
            <textarea value={JSON.stringify(form.manifest_json || {}, null, 2)} onChange={(event) => {
              try {
                setForm((current) => ({ ...current, manifest_json: JSON.parse(event.target.value || '{}') }))
              } catch {
                // ignore invalid json until user fixes it
              }
            }} rows={10} className="rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 font-mono text-sm text-white md:col-span-2" />
          </div>
          <div className="mt-5 flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200">
            <label className="flex items-center gap-2"><input type="checkbox" checked={Boolean(form.active)} onChange={(event) => setForm((current) => ({ ...current, active: event.target.checked }))} className="h-4 w-4" /> Active</label>
            <label className="flex items-center gap-2"><input type="checkbox" checked={Boolean(form.official)} onChange={(event) => setForm((current) => ({ ...current, official: event.target.checked }))} className="h-4 w-4" /> Official</label>
          </div>
          <button type="button" onClick={savePack} className="mt-5 w-full rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15">{selectedId ? 'Update pack' : 'Create pack'}</button>
        </section>
      </div>
    </div>
  )
}