import { useEffect, useState } from 'react'
import { apiRequest, addPluginFromUrl, deletePlugin } from '../api/client'
import { Puzzle, Check, Plus, Trash2 } from 'lucide-react'

interface Plugin {
  id: string
  name: string
  version: string
  desc: string
  enabled: boolean
  builtin?: boolean
  db_id?: number
}

export function PluginsPage() {
  const [plugins, setPlugins] = useState<Plugin[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [showAdd, setShowAdd] = useState(false)
  const [addUrl, setAddUrl] = useState('')
  const [adding, setAdding] = useState(false)
  const [addError, setAddError] = useState('')

  const loadPlugins = () =>
    apiRequest<{ plugins: Plugin[] }>('/plugin/list')
      .then((data) => setPlugins(data.plugins || []))
      .catch((err) => setError(err.message))

  useEffect(() => {
    setLoading(true)
    loadPlugins().finally(() => setLoading(false))
  }, [])

  const handleAdd = (e: React.FormEvent) => {
    e.preventDefault()
    const url = addUrl.trim()
    if (!url) return
    setAdding(true)
    setAddError('')
    addPluginFromUrl(url)
      .then(() => {
        setShowAdd(false)
        setAddUrl('')
        loadPlugins()
      })
      .catch((err) => setAddError(err.message))
      .finally(() => setAdding(false))
  }

  const handleDelete = (pluginId: string) => {
    if (!confirm('Remove this plugin?')) return
    deletePlugin(pluginId)
      .then(loadPlugins)
      .catch((err) => setError(err.message))
  }

  if (loading) return <div className="text-gray-500">Loading...</div>
  if (error) return <div className="p-4 rounded bg-red-100 text-red-700">{error}</div>

  return (
    <div>
      <div className="flex justify-between items-center mb-4">
        <h1 className="text-2xl font-bold text-gray-800 dark:text-white">Plugins</h1>
        <button
          onClick={() => setShowAdd(true)}
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium"
        >
          <Plus className="w-4 h-4" />
          Add from URL
        </button>
      </div>

      <div className="mb-4 p-3 rounded-lg bg-gray-100 dark:bg-gray-700/50 text-sm text-gray-600 dark:text-gray-400">
        Built-in extensions and third-party plugins. Add plugins from a JSON manifest URL (must include <code className="bg-gray-200 dark:bg-gray-600 px-1 rounded">id</code>, <code className="bg-gray-200 dark:bg-gray-600 px-1 rounded">name</code>, and optionally <code className="bg-gray-200 dark:bg-gray-600 px-1 rounded">version</code>, <code className="bg-gray-200 dark:bg-gray-600 px-1 rounded">desc</code>).
      </div>

      {showAdd && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-md">
            <h2 className="text-xl font-bold mb-4 text-gray-800 dark:text-white">Add Plugin from URL</h2>
            <form onSubmit={handleAdd} className="space-y-4">
              {addError && (
                <div className="p-2 rounded bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 text-sm">{addError}</div>
              )}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Manifest URL</label>
                <input
                  value={addUrl}
                  onChange={(e) => setAddUrl(e.target.value)}
                  placeholder="https://example.com/plugin.json"
                  className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700"
                  required
                />
              </div>
              <div className="flex gap-2 justify-end">
                <button type="button" onClick={() => { setShowAdd(false); setAddError('') }} className="px-4 py-2 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-700">
                  Cancel
                </button>
                <button type="submit" disabled={adding} className="px-4 py-2 bg-blue-600 text-white rounded-lg disabled:opacity-50">
                  {adding ? 'Adding...' : 'Add'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {plugins.map((p) => (
          <div
            key={p.id}
            className="bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700 p-4 flex items-start gap-3"
          >
            <Puzzle className="w-8 h-8 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 flex-wrap">
                <h3 className="font-semibold text-gray-900 dark:text-white">{p.name}</h3>
                {p.enabled && (
                  <span className="flex items-center gap-1 text-green-600 dark:text-green-400 text-xs">
                    <Check className="w-3 h-3" />
                    Enabled
                  </span>
                )}
                {!p.builtin && (
                  <button
                    onClick={() => handleDelete(p.id)}
                    className="p-1 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded ml-auto"
                    title="Remove"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                )}
              </div>
              <p className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">{p.desc}</p>
              <p className="text-xs text-gray-400 dark:text-gray-500 mt-1">v{p.version}{p.builtin ? ' (built-in)' : ''}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
