import React from 'react'
import { Head, Link, usePage } from '@inertiajs/react'
import Checkbox from '../../components/ui/Checkbox'
import NovaSelect from '../../components/ui/NovaSelect'

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 NovaCardsTemplateAdmin() {
  const { props } = usePage()
  const [templates, setTemplates] = React.useState(props.templates || [])
  const [selectedId, setSelectedId] = React.useState(null)
  const [form, setForm] = React.useState({
    slug: '',
    name: '',
    description: '',
    supported_formats: ['square'],
    active: true,
    official: true,
    order_num: templates.length,
    config_json: {
      font_preset: 'modern-sans',
      gradient_preset: 'midnight-nova',
      text_align: 'center',
      layout: 'quote_heavy',
      text_color: '#ffffff',
      overlay_style: 'dark-soft',
    },
  })
  const endpoints = props.endpoints || {}
  const formats = props.editorOptions?.formats || []
  const fonts = props.editorOptions?.font_presets || []
  const gradients = props.editorOptions?.gradient_presets || []

  function loadTemplate(template) {
    setSelectedId(template.id)
    setForm({
      slug: template.slug,
      name: template.name,
      description: template.description || '',
      preview_image: template.preview_image || null,
      supported_formats: template.supported_formats || [],
      active: Boolean(template.active),
      official: Boolean(template.official),
      order_num: template.order_num || 0,
      config_json: template.config_json || {},
    })
  }

  function resetForm() {
    setSelectedId(null)
    setForm({
      slug: '',
      name: '',
      description: '',
      supported_formats: ['square'],
      active: true,
      official: true,
      order_num: templates.length,
      config_json: {
        font_preset: 'modern-sans',
        gradient_preset: 'midnight-nova',
        text_align: 'center',
        layout: 'quote_heavy',
        text_color: '#ffffff',
        overlay_style: 'dark-soft',
      },
    })
  }

  async function saveTemplate() {
    const isExisting = Boolean(selectedId)
    const url = isExisting
      ? String(endpoints.updatePattern || '').replace('__TEMPLATE__', String(selectedId))
      : endpoints.store
    const response = await requestJson(url, {
      method: isExisting ? 'PATCH' : 'POST',
      body: form,
    })

    if (isExisting) {
      setTemplates((current) => current.map((template) => (template.id === selectedId ? response.template : template)))
    } else {
      setTemplates((current) => [...current, response.template])
      setSelectedId(response.template.id)
    }
  }

  function toggleFormat(key) {
    setForm((current) => {
      const exists = current.supported_formats.includes(key)
      return {
        ...current,
        supported_formats: exists ? current.supported_formats.filter((item) => item !== key) : [...current.supported_formats, key],
      }
    })
  }

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

      <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">Template system</p>
            <h1 className="mt-3 text-3xl font-semibold tracking-[-0.04em] text-white">Official Nova Cards templates</h1>
            <p className="mt-3 max-w-3xl text-sm leading-7 text-slate-300">Keep starter templates config-driven so the editor and render pipeline stay aligned as new card styles ship.</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 template</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,1.1fr)_minmax(0,1.4fr)]">
        <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 templates</div>
          <div className="space-y-3">
            {templates.map((template) => (
              <button key={template.id} type="button" onClick={() => loadTemplate(template)} className={`w-full rounded-[22px] border p-4 text-left transition ${selectedId === template.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">{template.name}</div>
                    <div className="mt-1 text-xs uppercase tracking-[0.18em] text-slate-500">{template.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">{template.supported_formats?.join(', ')}</span>
                </div>
                {template.description ? <div className="mt-2 text-sm text-slate-400">{template.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">Template 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="Template 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" />
            <div className="text-sm text-slate-300">
              <span className="mb-2 block">Font preset</span>
              <NovaSelect value={form.config_json?.font_preset || 'modern-sans'} onChange={(val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, font_preset: val } }))} options={fonts.map((f) => ({ value: f.key, label: f.label }))} searchable={false} />
            </div>
            <div className="text-sm text-slate-300">
              <span className="mb-2 block">Gradient preset</span>
              <NovaSelect value={form.config_json?.gradient_preset || 'midnight-nova'} onChange={(val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, gradient_preset: val } }))} options={gradients.map((g) => ({ value: g.key, label: g.label }))} searchable={false} />
            </div>
            <div className="text-sm text-slate-300">
              <span className="mb-2 block">Layout preset</span>
              <NovaSelect value={form.config_json?.layout || 'quote_heavy'} onChange={(val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, layout: val } }))} options={['quote_heavy', 'author_emphasis', 'centered', 'minimal'].map((v) => ({ value: v, label: v }))} searchable={false} />
            </div>
            <div className="text-sm text-slate-300">
              <span className="mb-2 block">Text alignment</span>
              <NovaSelect value={form.config_json?.text_align || 'center'} onChange={(val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, text_align: val } }))} options={['left', 'center', 'right'].map((v) => ({ value: v, label: v }))} searchable={false} />
            </div>
            <div className="text-sm text-slate-300">
              <span className="mb-2 block">Overlay style</span>
              <NovaSelect value={form.config_json?.overlay_style || 'dark-soft'} onChange={(val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, overlay_style: val } }))} options={['none', 'dark-soft', 'dark-strong', 'light-soft'].map((v) => ({ value: v, label: v }))} searchable={false} />
            </div>
            <label className="text-sm text-slate-300">
              <span className="mb-2 block">Text color</span>
              <input type="color" value={form.config_json?.text_color || '#ffffff'} onChange={(event) => setForm((current) => ({ ...current, config_json: { ...current.config_json, text_color: event.target.value } }))} className="h-12 w-full rounded-2xl border border-white/10 bg-[#0d1726] p-2" />
            </label>
          </div>
          <div className="mt-5">
            <div className="mb-3 text-sm font-semibold uppercase tracking-[0.18em] text-slate-400">Supported formats</div>
            <div className="flex flex-wrap gap-3">
              {formats.map((format) => (
                <div key={format.key} className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-slate-200">
                  <Checkbox checked={form.supported_formats.includes(format.key)} onChange={() => toggleFormat(format.key)} label={format.label} />
                </div>
              ))}
            </div>
          </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">
            <Checkbox checked={Boolean(form.active)} onChange={(event) => setForm((current) => ({ ...current, active: event.target.checked }))} label="Active" />
            <Checkbox checked={Boolean(form.official)} onChange={(event) => setForm((current) => ({ ...current, official: event.target.checked }))} label="Official" />
          </div>
          <button type="button" onClick={saveTemplate} 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 template' : 'Create template'}</button>
        </section>
      </div>
    </div>
  )
}