import { useEffect, useState } from 'react'
import { Puzzle, Link, RefreshCw } from 'lucide-react'

interface Script {
  id: string
  name: string
  description: string
  version: string
  author: string
  tags: string[]
  usage_count: number
  avg_saving: number
  status: string
  created_at: string
  bss_version?: string
  chain_ids?: string[]
}

export default function SkillsLibrary() {
  const [scripts, setScripts] = useState<Script[]>([])
  const [loading, setLoading] = useState(true)
  const [query, setQuery] = useState('')

  const load = () => {
    setLoading(true)
    fetch('/bibividi/api/scripts')
      .then(r => r.json())
      .then(setScripts)
      .catch(() => {})
      .finally(() => setLoading(false))
  }

  useEffect(() => { load() }, [])

  const filtered = scripts.filter(s =>
    !query ||
    s.name.toLowerCase().includes(query.toLowerCase()) ||
    s.id.toLowerCase().includes(query.toLowerCase()) ||
    s.description.toLowerCase().includes(query.toLowerCase()) ||
    s.tags.some(t => t.toLowerCase().includes(query.toLowerCase()))
  )

  return (
    <div>
      <div className="page-title">
        <Puzzle size={20} color="var(--accent-light)" />
        Skills Library
        <span className="muted fine" style={{ marginLeft: 4 }}>({scripts.length} installed)</span>
        <button className="btn btn-ghost" style={{ marginLeft: 'auto', padding: '5px 10px' }} onClick={load}>
          <RefreshCw size={13} />
        </button>
      </div>

      {/* Search */}
      <div style={{ marginBottom: 16 }}>
        <input
          type="text"
          placeholder="Filter by name, id, tag…"
          value={query}
          onChange={e => setQuery(e.target.value)}
          style={{
            width: '100%',
            maxWidth: 360,
            padding: '7px 12px',
            background: 'var(--bg2)',
            border: '1px solid var(--border)',
            borderRadius: 6,
            color: 'var(--text)',
            font: 'inherit',
            fontSize: 13,
          }}
        />
      </div>

      {loading && <p className="muted">Loading…</p>}

      {!loading && filtered.length === 0 && (
        <div className="empty-state">
          <Puzzle size={32} />
          <p>{query ? 'No skills match your search.' : 'No skills installed yet.'}</p>
          <p className="fine" style={{ marginTop: 4 }}>
            Add skills with <code>bibividi add &lt;pack-dir&gt;</code>
          </p>
        </div>
      )}

      <div className="skills-grid">
        {filtered.map(s => (
          <div key={s.id} className="skill-card">
            <div className="skill-card-header">
              <div>
                <strong>{s.name}</strong>
                <div className="mono fine muted" style={{ marginTop: 2 }}>{s.id}</div>
              </div>
              <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
                {s.chain_ids && s.chain_ids.length > 0 && (
                  <span className="badge badge-purple" title="BSS chain skill">
                    <Link size={10} style={{ display: 'inline', verticalAlign: 'middle' }} /> chain
                  </span>
                )}
                <span className="badge badge-gray">v{s.version}</span>
              </div>
            </div>

            <p className="muted" style={{ fontSize: 12, lineHeight: 1.4 }}>
              {s.description.length > 120 ? s.description.slice(0, 120) + '…' : s.description}
            </p>

            {s.tags.length > 0 && (
              <div className="tags">
                {s.tags.map(t => <span key={t} className="tag">{t}</span>)}
              </div>
            )}

            <div className="skill-card-meta">
              <span>
                <span className="green" style={{ fontWeight: 600 }}>
                  {Math.round(s.avg_saving * 100)}%
                </span>
                {' '}avg saving
              </span>
              <span>{s.usage_count.toLocaleString()} uses</span>
              {s.author && <span className="muted">by {s.author}</span>}
            </div>

            <div className="bar-wrap" style={{ height: 4 }}>
              <div
                className="bar-fill"
                style={{
                  width: `${Math.round(s.avg_saving * 100)}%`,
                  background: 'var(--green)',
                }}
              />
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
