import { useEffect, useState } from 'react'
import { apiRequest } from '../api/client'
import { Play, Square, RotateCw, Loader2 } from 'lucide-react'

interface Service {
  id: string
  name: string
  unit: string
  status: string
}

export function ServicesPage() {
  const [services, setServices] = useState<Service[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [actionId, setActionId] = useState<string | null>(null)

  const load = () => {
    setLoading(true)
    apiRequest<{ services: Service[] }>('/service/list')
      .then((data) => setServices(data.services || []))
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false))
  }

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

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

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

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

  const isActive = (status: string) => status === 'active' || status === 'activating'

  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">Services</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"
        >
          <RotateCw className="w-4 h-4" />
          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-gray-100 dark:bg-gray-700/50 text-sm text-gray-600 dark:text-gray-400">
        Control system services via systemctl. Requires panel to run with sufficient privileges.
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
        <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
          <thead className="bg-gray-50 dark:bg-gray-700">
            <tr>
              <th className="px-4 py-2 text-left text-sm font-medium text-gray-700 dark:text-gray-300">Service</th>
              <th className="px-4 py-2 text-left text-sm font-medium text-gray-700 dark:text-gray-300">Unit</th>
              <th className="px-4 py-2 text-left text-sm font-medium text-gray-700 dark:text-gray-300">Status</th>
              <th className="px-4 py-2 text-right text-sm font-medium text-gray-700 dark:text-gray-300">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
            {services.map((s) => (
              <tr key={s.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/30">
                <td className="px-4 py-2 text-gray-900 dark:text-white">{s.name}</td>
                <td className="px-4 py-2 font-mono text-gray-600 dark:text-gray-400 text-sm">{s.unit}</td>
                <td className="px-4 py-2">
                  <span
                    className={`text-sm ${
                      isActive(s.status) ? 'text-green-600 dark:text-green-400' : 'text-gray-500 dark:text-gray-400'
                    }`}
                  >
                    {s.status}
                  </span>
                </td>
                <td className="px-4 py-2 text-right">
                  <span className="flex gap-1 justify-end">
                    {isActive(s.status) ? (
                      <>
                        <button
                          onClick={() => handleRestart(s.id)}
                          disabled={!!actionId}
                          className="p-2 text-amber-600 hover:bg-amber-50 dark:hover:bg-amber-900/20 rounded disabled:opacity-50"
                          title="Restart"
                        >
                          {actionId === s.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <RotateCw className="w-4 h-4" />}
                        </button>
                        <button
                          onClick={() => handleStop(s.id)}
                          disabled={!!actionId}
                          className="p-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded disabled:opacity-50"
                          title="Stop"
                        >
                          <Square className="w-4 h-4" />
                        </button>
                      </>
                    ) : (
                      <button
                        onClick={() => handleStart(s.id)}
                        disabled={!!actionId}
                        className="p-2 text-green-600 hover:bg-green-50 dark:hover:bg-green-900/20 rounded disabled:opacity-50"
                        title="Start"
                      >
                        {actionId === s.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
                      </button>
                    )}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
