import { useEffect, useState } from 'react'
import { apiRequest } from '../api/client'
import { Check, X, Loader2, Package } from 'lucide-react'

interface Software {
  id: string
  name: string
  desc: string
  pkg: string
  installed: boolean
  version: string
}

export function SoftPage() {
  const [software, setSoftware] = useState<Software[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [actionId, setActionId] = useState<string | null>(null)

  const load = () => {
    setLoading(true)
    apiRequest<{ software: Software[] }>('/soft/list')
      .then((data) => setSoftware(data.software || []))
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false))
  }

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

  const handleInstall = (id: string) => {
    setActionId(id)
    setError('')
    apiRequest<{ status: boolean }>(`/soft/install/${id}`, { method: 'POST' })
      .then(() => load())
      .catch((err) => setError(err.message))
      .finally(() => setActionId(null))
  }

  const handleUninstall = (id: string, name: string) => {
    if (!confirm(`Uninstall ${name}?`)) return
    setActionId(id)
    setError('')
    apiRequest<{ status: boolean }>(`/soft/uninstall/${id}`, { method: 'POST' })
      .then(() => load())
      .catch((err) => setError(err.message))
      .finally(() => setActionId(null))
  }

  if (loading) return <div className="text-gray-500">Loading...</div>

  return (
    <div>
      <div className="flex justify-between items-center mb-4">
        <h1 className="text-2xl font-bold text-gray-800 dark:text-white">App Store</h1>
        <button
          onClick={load}
          className="flex items-center gap-2 px-4 py-2 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 rounded-lg"
        >
          Refresh
        </button>
      </div>

      {error && (
        <div className="mb-4 p-3 rounded-lg bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300">
          {error}
        </div>
      )}

      <div className="mb-4 p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 text-amber-800 dark:text-amber-200 text-sm">
        Install/uninstall via apt. Panel must run with sufficient privileges. Target: Debian/Ubuntu.
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {software.map((s) => (
          <div
            key={s.id}
            className="bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700 p-4 flex flex-col"
          >
            <div className="flex items-start justify-between gap-2 mb-2">
              <div className="flex items-center gap-2">
                <Package className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0" />
                <div>
                  <h3 className="font-semibold text-gray-900 dark:text-white">{s.name}</h3>
                  <p className="text-sm text-gray-500 dark:text-gray-400">{s.desc}</p>
                </div>
              </div>
              {s.installed ? (
                <span className="flex items-center gap-1 text-green-600 dark:text-green-400 text-sm flex-shrink-0">
                  <Check className="w-4 h-4" />
                  {s.version || 'Installed'}
                </span>
              ) : (
                <span className="flex items-center gap-1 text-gray-500 text-sm flex-shrink-0">
                  <X className="w-4 h-4" />
                  Not installed
                </span>
              )}
            </div>
            <div className="mt-auto pt-3">
              {s.installed ? (
                <button
                  onClick={() => handleUninstall(s.id, s.name)}
                  disabled={actionId === s.id}
                  className="w-full px-3 py-2 text-sm rounded-lg border border-red-200 dark:border-red-800 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 disabled:opacity-50 flex items-center justify-center gap-2"
                >
                  {actionId === s.id ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    'Uninstall'
                  )}
                </button>
              ) : (
                <button
                  onClick={() => handleInstall(s.id)}
                  disabled={actionId === s.id}
                  className="w-full px-3 py-2 text-sm rounded-lg bg-blue-600 hover:bg-blue-700 text-white disabled:opacity-50 flex items-center justify-center gap-2"
                >
                  {actionId === s.id ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    'Install'
                  )}
                </button>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
