'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'

const KIND_LABELS: Record<string, string> = {
  SALE: 'For Sale',
  RENT: 'For Rent',
  VACATION: 'Vacation',
}

interface CategoryRow {
  id: string
  slug: string
  name: string
  nameEs: string | null
  nameFr: string | null
  kind: string
  parentId: string | null
  sortOrder: number
  active: boolean
  _count: { rentals: number; listings: number }
}

interface Props {
  categories: CategoryRow[]
}

const emptyDraft = {
  name: '',
  nameEs: '',
  nameFr: '',
  slug: '',
  kind: 'SALE',
  parentId: '',
  sortOrder: '0',
}

export function CategoryManager({ categories }: Props) {
  const router = useRouter()
  const [busy, setBusy] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [showForm, setShowForm] = useState(false)
  const [draft, setDraft] = useState(emptyDraft)

  const roots = categories.filter((c) => !c.parentId)

  async function call(url: string, method: string, body?: unknown) {
    setBusy(url)
    setError(null)
    try {
      const res = await fetch(url, {
        method,
        headers: body ? { 'Content-Type': 'application/json' } : undefined,
        body: body ? JSON.stringify(body) : undefined,
      })
      const json = await res.json().catch(() => ({}))
      if (!res.ok) {
        setError(json.error || `Error ${res.status}`)
        return false
      }
      router.refresh()
      return true
    } catch {
      setError('Network error')
      return false
    } finally {
      setBusy(null)
    }
  }

  async function create(e: React.FormEvent) {
    e.preventDefault()
    const ok = await call('/api/admin/categories', 'POST', {
      name: draft.name.trim(),
      nameEs: draft.nameEs.trim() || undefined,
      nameFr: draft.nameFr.trim() || undefined,
      slug: draft.slug.trim(),
      kind: draft.kind,
      parentId: draft.parentId || undefined,
      sortOrder: Number(draft.sortOrder) || 0,
    })
    if (ok) {
      setDraft(emptyDraft)
      setShowForm(false)
    }
  }

  async function toggleActive(c: CategoryRow) {
    await call(`/api/admin/categories/${c.id}`, 'PATCH', { active: !c.active })
  }

  async function remove(c: CategoryRow) {
    const count = c._count.rentals + c._count.listings
    const msg =
      count > 0
        ? `Delete "${c.name}"? ${count} propert${count === 1 ? 'y' : 'ies'} will lose its category (they are not deleted).`
        : `Delete "${c.name}"?`
    if (!confirm(msg)) return
    await call(`/api/admin/categories/${c.id}`, 'DELETE')
  }

  const input =
    'w-full px-3 py-2 border rounded text-sm focus:border-[#374527] focus:outline-none'

  return (
    <div>
      {error && (
        <p role="alert" className="mb-4 rounded bg-red-50 p-3 text-sm text-red-700">
          {error}
        </p>
      )}

      <div className="mb-6 flex items-center justify-between">
        <h1 className="text-3xl font-bold text-[#1D2019]">Categories</h1>
        <button
          onClick={() => setShowForm((s) => !s)}
          className="rounded-lg bg-[#374527] px-4 py-2 text-sm font-medium text-white hover:bg-[#1D2019]"
        >
          {showForm ? 'Cancel' : 'New category'}
        </button>
      </div>

      {showForm && (
        <form onSubmit={create} className="mb-8 rounded-lg border bg-white p-6">
          <div className="mb-4 grid grid-cols-2 gap-4">
            <div>
              <label className="mb-1 block text-sm font-medium">Name (EN) *</label>
              <input
                className={input}
                required
                value={draft.name}
                onChange={(e) => setDraft({ ...draft, name: e.target.value })}
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Slug *</label>
              <input
                className={input}
                required
                pattern="[a-z0-9-]+"
                placeholder="vacacional-villa"
                value={draft.slug}
                onChange={(e) => setDraft({ ...draft, slug: e.target.value })}
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Name (ES)</label>
              <input
                className={input}
                value={draft.nameEs}
                onChange={(e) => setDraft({ ...draft, nameEs: e.target.value })}
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Name (FR)</label>
              <input
                className={input}
                value={draft.nameFr}
                onChange={(e) => setDraft({ ...draft, nameFr: e.target.value })}
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Kind *</label>
              <select
                className={input}
                value={draft.kind}
                onChange={(e) => setDraft({ ...draft, kind: e.target.value })}
              >
                {Object.entries(KIND_LABELS).map(([k, label]) => (
                  <option key={k} value={k}>
                    {label}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Parent</label>
              <select
                className={input}
                value={draft.parentId}
                onChange={(e) => setDraft({ ...draft, parentId: e.target.value })}
              >
                <option value="">— (root) —</option>
                {roots.map((r) => (
                  <option key={r.id} value={r.id}>
                    {r.name}
                  </option>
                ))}
              </select>
            </div>
          </div>
          <button
            type="submit"
            disabled={busy !== null}
            className="rounded-lg bg-[#374527] px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
          >
            Create
          </button>
        </form>
      )}

      <div className="space-y-6">
        {roots.map((root) => {
          const children = categories.filter((c) => c.parentId === root.id)
          const total =
            root._count.rentals +
            root._count.listings +
            children.reduce((a, c) => a + c._count.rentals + c._count.listings, 0)

          return (
            <div key={root.id} className="overflow-hidden rounded-lg border bg-white">
              <div className="flex items-center justify-between bg-gray-50 px-4 py-3">
                <div className="flex items-center gap-3">
                  <span className="rounded bg-[#1D2019] px-2 py-0.5 text-xs font-semibold text-white">
                    {KIND_LABELS[root.kind] ?? root.kind}
                  </span>
                  <span className="font-semibold">{root.name}</span>
                  <code className="text-xs text-gray-500">{root.slug}</code>
                  <span className="text-xs text-gray-500">{total} properties</span>
                  {!root.active && (
                    <span className="rounded bg-red-100 px-2 py-0.5 text-xs text-red-700">
                      inactive
                    </span>
                  )}
                </div>
                <div className="flex gap-2">
                  <button
                    onClick={() => toggleActive(root)}
                    disabled={busy !== null}
                    className="rounded border px-3 py-1 text-xs hover:bg-gray-100 disabled:opacity-50"
                  >
                    {root.active ? 'Deactivate' : 'Activate'}
                  </button>
                  <button
                    onClick={() => remove(root)}
                    disabled={busy !== null}
                    className="rounded border border-red-300 px-3 py-1 text-xs text-red-700 hover:bg-red-50 disabled:opacity-50"
                  >
                    Delete
                  </button>
                </div>
              </div>

              {children.length > 0 && (
                <ul className="divide-y">
                  {children.map((child) => {
                    const n = child._count.rentals + child._count.listings
                    return (
                      <li
                        key={child.id}
                        className="flex items-center justify-between px-4 py-2 pl-10"
                      >
                        <div className="flex items-center gap-3">
                          <span className="text-sm">{child.name}</span>
                          <code className="text-xs text-gray-500">{child.slug}</code>
                          <span className="text-xs text-gray-500">{n} properties</span>
                          {!child.active && (
                            <span className="rounded bg-red-100 px-2 py-0.5 text-xs text-red-700">
                              inactive
                            </span>
                          )}
                        </div>
                        <div className="flex gap-2">
                          <button
                            onClick={() => toggleActive(child)}
                            disabled={busy !== null}
                            className="rounded border px-3 py-1 text-xs hover:bg-gray-100 disabled:opacity-50"
                          >
                            {child.active ? 'Deactivate' : 'Activate'}
                          </button>
                          <button
                            onClick={() => remove(child)}
                            disabled={busy !== null}
                            className="rounded border border-red-300 px-3 py-1 text-xs text-red-700 hover:bg-red-50 disabled:opacity-50"
                          >
                            Delete
                          </button>
                        </div>
                      </li>
                    )
                  })}
                </ul>
              )}
            </div>
          )
        })}
      </div>
    </div>
  )
}