import { useMemo, useState } from 'react'
import { Star, X } from 'lucide-react'
import { useAddonRegistry, useInstallAddon, useInstalledAddons } from '../../hooks/useAddons'

export function AddonBrowserModal({
  name,
  onClose
}: {
  name: string
  onClose: () => void
}): React.JSX.Element {
  const [query, setQuery] = useState('')
  const { data: registry, isLoading } = useAddonRegistry()
  const { data: installed } = useInstalledAddons(name)
  const installAddon = useInstallAddon(name)

  const installedRepos = useMemo(
    () => new Set((installed ?? []).map((a) => a.Repository)),
    [installed]
  )

  const filtered = useMemo(() => {
    if (!registry) return []
    const q = query.trim().toLowerCase()
    if (!q) return registry
    return registry.filter(
      (entry) =>
        entry.title.toLowerCase().includes(q) || entry.description.toLowerCase().includes(q)
    )
  }, [registry, query])

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-8">
      <div className="flex h-full w-full max-w-2xl flex-col rounded-xl bg-white shadow-2xl dark:bg-neutral-900">
        <div className="flex items-center justify-between border-b border-neutral-200 px-4 py-3 dark:border-neutral-800">
          <h2 className="text-sm font-semibold">Browse Add-ons</h2>
          <button
            type="button"
            onClick={onClose}
            className="rounded p-1 text-neutral-400 hover:bg-neutral-100 hover:text-neutral-700 dark:hover:bg-neutral-800 dark:hover:text-neutral-200"
          >
            <X size={16} />
          </button>
        </div>
        <div className="border-b border-neutral-200 p-3 dark:border-neutral-800">
          <input
            autoFocus
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search add-ons…"
            className="w-full rounded-md border border-neutral-300 px-3 py-1.5 text-sm dark:border-neutral-700 dark:bg-neutral-950"
          />
        </div>
        <div className="flex-1 overflow-y-auto">
          {isLoading ? (
            <p className="p-4 text-sm text-neutral-500">Loading add-on registry…</p>
          ) : filtered.length === 0 ? (
            <p className="p-4 text-sm text-neutral-500">No add-ons match &quot;{query}&quot;.</p>
          ) : (
            <ul className="divide-y divide-neutral-200 dark:divide-neutral-800">
              {filtered.map((entry) => {
                const isInstalled = installedRepos.has(entry.title)
                return (
                  <li
                    key={entry.repo_id}
                    className="flex items-center justify-between gap-4 px-4 py-3"
                  >
                    <div className="min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="truncate text-sm font-medium">{entry.title}</span>
                        <span className="flex items-center gap-0.5 text-xs text-neutral-400">
                          <Star size={11} /> {entry.stars}
                        </span>
                      </div>
                      <p className="truncate text-xs text-neutral-500 dark:text-neutral-400">
                        {entry.description}
                      </p>
                    </div>
                    <button
                      type="button"
                      disabled={isInstalled || installAddon.isPending}
                      onClick={() => installAddon.mutate(entry.title)}
                      className="flex-shrink-0 rounded-md border border-neutral-300 px-3 py-1 text-xs font-medium hover:bg-neutral-50 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-700 dark:hover:bg-neutral-800"
                    >
                      {isInstalled ? 'Installed' : 'Install'}
                    </button>
                  </li>
                )
              })}
            </ul>
          )}
        </div>
      </div>
    </div>
  )
}
