import React from 'react'
import { Head, Link, usePage } from '@inertiajs/react'
import Checkbox from '../../components/ui/Checkbox'
import DateTimePicker from '../../components/ui/DateTimePicker'
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 NovaCardsChallengeAdmin() {
  const { props } = usePage()
  const [challenges, setChallenges] = React.useState(props.challenges || [])
  const [selectedId, setSelectedId] = React.useState(null)
  const [form, setForm] = React.useState({ slug: '', title: '', description: '', prompt: '', rules_json: {}, status: 'draft', official: true, featured: false, winner_card_id: '', starts_at: '', ends_at: '' })
  const endpoints = props.endpoints || {}
  const cards = props.cards || []

  function loadChallenge(challenge) {
    setSelectedId(challenge.id)
    setForm({
      slug: challenge.slug,
      title: challenge.title,
      description: challenge.description || '',
      prompt: challenge.prompt || '',
      rules_json: challenge.rules_json || {},
      status: challenge.status || 'draft',
      official: Boolean(challenge.official),
      featured: Boolean(challenge.featured),
      winner_card_id: challenge.winner_card_id || '',
      starts_at: challenge.starts_at || '',
      ends_at: challenge.ends_at || '',
    })
  }

  function resetForm() {
    setSelectedId(null)
    setForm({ slug: '', title: '', description: '', prompt: '', rules_json: {}, status: 'draft', official: true, featured: false, winner_card_id: '', starts_at: '', ends_at: '' })
  }

  async function saveChallenge() {
    const isExisting = Boolean(selectedId)
    const url = isExisting ? String(endpoints.updatePattern || '').replace('__CHALLENGE__', String(selectedId)) : endpoints.store
    const response = await requestJson(url, { method: isExisting ? 'PATCH' : 'POST', body: { ...form, winner_card_id: form.winner_card_id || null } })
    if (isExisting) {
      setChallenges((current) => current.map((challenge) => (challenge.id === selectedId ? response.challenge : challenge)))
    } else {
      setChallenges((current) => [...current, response.challenge])
      setSelectedId(response.challenge.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 Challenges" />

      <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">Challenge system</p>
            <h1 className="mt-3 text-3xl font-semibold tracking-[-0.04em] text-white">Nova Cards challenge programming</h1>
            <p className="mt-3 max-w-3xl text-sm leading-7 text-slate-300">Program official challenge prompts, track featured runs, and connect winner cards.</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 challenge</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 challenges</div>
          <div className="space-y-3">
            {challenges.map((challenge) => (
              <button key={challenge.id} type="button" onClick={() => loadChallenge(challenge)} className={`w-full rounded-[22px] border p-4 text-left transition ${selectedId === challenge.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">{challenge.title}</div>
                    <div className="mt-1 text-xs uppercase tracking-[0.18em] text-slate-500">{challenge.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">{challenge.status}</span>
                </div>
                {challenge.description ? <div className="mt-2 text-sm text-slate-400">{challenge.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">Challenge editor</div>
          <div className="grid gap-4 md:grid-cols-2">
            <input value={form.title} onChange={(event) => setForm((current) => ({ ...current, title: event.target.value }))} placeholder="Title" 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" />
            <textarea value={form.prompt} onChange={(event) => setForm((current) => ({ ...current, prompt: event.target.value }))} placeholder="Prompt" rows={4} 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">Status</span>
              <NovaSelect value={form.status} onChange={(val) => setForm((current) => ({ ...current, status: val }))} searchable={false} options={['draft', 'active', 'completed', 'archived'].map((s) => ({ value: s, label: s }))} />
            </div>
            <div className="text-sm text-slate-300">
              <span className="mb-2 block">Winner card</span>
              <NovaSelect value={String(form.winner_card_id || '')} onChange={(val) => setForm((current) => ({ ...current, winner_card_id: val }))} placeholder="No winner" options={cards.map((c) => ({ value: String(c.id), label: c.title }))} />
            </div>
            <div className="text-sm text-slate-300">
              <span className="mb-2 block">Starts at</span>
              <DateTimePicker value={form.starts_at} onChange={(nextValue) => setForm((current) => ({ ...current, starts_at: nextValue }))} placeholder="Starts at" clearable className="bg-[#0d1726]" />
            </div>
            <div className="text-sm text-slate-300">
              <span className="mb-2 block">Ends at</span>
              <DateTimePicker value={form.ends_at} onChange={(nextValue) => setForm((current) => ({ ...current, ends_at: nextValue }))} placeholder="Ends at" clearable className="bg-[#0d1726]" />
            </div>
            <textarea value={JSON.stringify(form.rules_json || {}, null, 2)} onChange={(event) => {
              try {
                setForm((current) => ({ ...current, rules_json: JSON.parse(event.target.value || '{}') }))
              } catch {
                // ignore invalid json until fixed
              }
            }} 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">
            <Checkbox checked={Boolean(form.official)} onChange={(event) => setForm((current) => ({ ...current, official: event.target.checked }))} label="Official" />
            <Checkbox checked={Boolean(form.featured)} onChange={(event) => setForm((current) => ({ ...current, featured: event.target.checked }))} label="Featured" />
          </div>
          <button type="button" onClick={saveChallenge} 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 challenge' : 'Create challenge'}</button>
        </section>
      </div>
    </div>
  )
}