import { useCallback, useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { SwaggerDocs } from './SwaggerDocs'

const STORAGE_KEY = 'alrahma_docs_jwt'

export function AdminDocs() {
  const [token, setToken] = useState('')
  const [saved, setSaved] = useState<string | null>(null)

  useEffect(() => {
    try {
      const t = localStorage.getItem(STORAGE_KEY)
      if (t) {
        setSaved(t)
      }
    } catch {
      /* ignore */
    }
  }, [])

  const authHeader = saved ? `Bearer ${saved}` : null

  const saveToken = useCallback(() => {
    const t = token.trim()
    if (!t) {
      localStorage.removeItem(STORAGE_KEY)
      setSaved(null)
      return
    }
    localStorage.setItem(STORAGE_KEY, t)
    setSaved(t)
  }, [token])

  return (
    <div className="admin-docs-shell">
      <header className="docs-toolbar">
        <Link to="/docs">Public docs</Link>
        <label>
          JWT (admin){' '}
          <input
            type="password"
            autoComplete="off"
            value={token}
            placeholder={saved ? '•••••••• (saved)' : ''}
            onChange={(e) => setToken(e.target.value)}
          />
        </label>
        <button type="button" onClick={saveToken}>
          Save token
        </button>
        {saved ? (
          <button
            type="button"
            onClick={() => {
              localStorage.removeItem(STORAGE_KEY)
              setSaved(null)
              setToken('')
            }}
          >
            Clear
          </button>
        ) : null}
      </header>
      <SwaggerDocs bootstrapPath="/api/docs" authorization={authHeader} />
    </div>
  )
}
