import { useEffect, useState } from 'react'
import { apiRequest, listDockerContainers, listDockerImages, dockerPull, dockerRun } from '../api/client'
import { Play, Square, RotateCw, Loader2, Plus, Download } from 'lucide-react'

interface Container {
  id: string
  id_full: string
  image: string
  status: string
  names: string
  ports: string
}

interface DockerImage {
  repository: string
  tag: string
  id: string
  size: string
}

export function DockerPage() {
  const [containers, setContainers] = useState<Container[]>([])
  const [images, setImages] = useState<DockerImage[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [actionId, setActionId] = useState<string | null>(null)
  const [showRun, setShowRun] = useState(false)
  const [runImage, setRunImage] = useState('')
  const [runName, setRunName] = useState('')
  const [runPorts, setRunPorts] = useState('')
  const [running, setRunning] = useState(false)
  const [pullImage, setPullImage] = useState('')
  const [pulling, setPulling] = useState(false)

  const load = () => {
    setLoading(true)
    Promise.all([
      listDockerContainers(),
      listDockerImages(),
    ])
      .then(([contData, imgData]) => {
        setContainers(contData.containers || [])
        setImages(imgData.images || [])
        setError(contData.error || imgData.error || '')
      })
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false))
  }

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

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

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

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

  const isRunning = (status: string) =>
    status.toLowerCase().startsWith('up') || status.toLowerCase().includes('running')

  const handleRun = (e: React.FormEvent) => {
    e.preventDefault()
    if (!runImage.trim()) return
    setRunning(true)
    dockerRun(runImage.trim(), runName.trim() || undefined, runPorts.trim() || undefined)
      .then(() => {
        setShowRun(false)
        setRunImage('')
        setRunName('')
        setRunPorts('')
        load()
      })
      .catch((err) => setError(err.message))
      .finally(() => setRunning(false))
  }

  const handlePull = () => {
    if (!pullImage.trim()) return
    setPulling(true)
    dockerPull(pullImage.trim())
      .then(() => {
        setPullImage('')
        load()
      })
      .catch((err) => setError(err.message))
      .finally(() => setPulling(false))
  }

  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">Docker</h1>
        <div className="flex gap-2">
          <div className="flex gap-1">
            <input
              value={pullImage}
              onChange={(e) => setPullImage(e.target.value)}
              placeholder="nginx:latest"
              className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-sm w-40"
            />
            <button
              onClick={handlePull}
              disabled={pulling || !pullImage.trim()}
              className="flex items-center gap-1 px-3 py-2 bg-amber-600 hover:bg-amber-700 text-white rounded-lg disabled:opacity-50"
            >
              {pulling ? <Loader2 className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}
              Pull
            </button>
          </div>
          <button
            onClick={() => setShowRun(true)}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg"
          >
            <Plus className="w-4 h-4" />
            Run Container
          </button>
          <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>
      </div>

      {showRun && (
        <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">Run Container</h2>
            <form onSubmit={handleRun} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Image</label>
                <input
                  value={runImage}
                  onChange={(e) => setRunImage(e.target.value)}
                  placeholder="nginx:latest"
                  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>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Name (optional)</label>
                <input
                  value={runName}
                  onChange={(e) => setRunName(e.target.value)}
                  placeholder="my-nginx"
                  className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Ports (optional, e.g. 80:80 or 8080:80)</label>
                <input
                  value={runPorts}
                  onChange={(e) => setRunPorts(e.target.value)}
                  placeholder="80:80"
                  className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700"
                />
              </div>
              <div className="flex gap-2 justify-end">
                <button type="button" onClick={() => setShowRun(false)} className="px-4 py-2 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-700">
                  Cancel
                </button>
                <button type="submit" disabled={running} className="px-4 py-2 bg-blue-600 text-white rounded-lg disabled:opacity-50">
                  {running ? 'Starting...' : 'Run'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {error && (
        <div className="mb-4 p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 text-amber-800 dark:text-amber-200">
          {error}
        </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">
                Container
              </th>
              <th className="px-4 py-2 text-left text-sm font-medium text-gray-700 dark:text-gray-300">
                Image
              </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-left text-sm font-medium text-gray-700 dark:text-gray-300">
                Ports
              </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">
            {containers.length === 0 ? (
              <tr>
                <td colSpan={5} className="px-4 py-8 text-center text-gray-500">
                  No containers. Install Docker and run some containers.
                </td>
              </tr>
            ) : (
              containers.map((c) => (
                <tr key={c.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/30">
                  <td className="px-4 py-2 font-mono text-gray-900 dark:text-white">{c.names || c.id}</td>
                  <td className="px-4 py-2 text-gray-600 dark:text-gray-400">{c.image}</td>
                  <td className="px-4 py-2">
                    <span
                      className={`text-sm ${
                        isRunning(c.status)
                          ? 'text-green-600 dark:text-green-400'
                          : 'text-gray-500 dark:text-gray-400'
                      }`}
                    >
                      {c.status}
                    </span>
                  </td>
                  <td className="px-4 py-2 text-gray-600 dark:text-gray-400 text-sm max-w-xs truncate">
                    {c.ports || '-'}
                  </td>
                  <td className="px-4 py-2 text-right">
                    <span className="flex gap-1 justify-end">
                      {isRunning(c.status) ? (
                        <>
                          <button
                            onClick={() => handleRestart(c.id_full)}
                            disabled={actionId === c.id_full}
                            className="p-2 text-amber-600 hover:bg-amber-50 dark:hover:bg-amber-900/20 rounded disabled:opacity-50"
                            title="Restart"
                          >
                            {actionId === c.id_full ? (
                              <Loader2 className="w-4 h-4 animate-spin" />
                            ) : (
                              <RotateCw className="w-4 h-4" />
                            )}
                          </button>
                          <button
                            onClick={() => handleStop(c.id_full)}
                            disabled={actionId === c.id_full}
                            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(c.id_full)}
                          disabled={actionId === c.id_full}
                          className="p-2 text-green-600 hover:bg-green-50 dark:hover:bg-green-900/20 rounded disabled:opacity-50"
                          title="Start"
                        >
                          {actionId === c.id_full ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : (
                            <Play className="w-4 h-4" />
                          )}
                        </button>
                      )}
                    </span>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      <div className="mt-8">
        <h2 className="text-lg font-bold mb-3 text-gray-800 dark:text-white">Images</h2>
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
          {images.length === 0 ? (
            <div className="px-4 py-8 text-center text-gray-500">No images. Pull one above.</div>
          ) : (
            <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">Repository</th>
                  <th className="px-4 py-2 text-left text-sm font-medium text-gray-700 dark:text-gray-300">Tag</th>
                  <th className="px-4 py-2 text-left text-sm font-medium text-gray-700 dark:text-gray-300">Size</th>
                  <th className="px-4 py-2 text-right text-sm font-medium text-gray-700 dark:text-gray-300">Action</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                {images.map((img) => (
                  <tr key={img.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/30">
                    <td className="px-4 py-2 font-mono text-gray-900 dark:text-white">{img.repository}</td>
                    <td className="px-4 py-2 text-gray-600 dark:text-gray-400">{img.tag}</td>
                    <td className="px-4 py-2 text-gray-600 dark:text-gray-400">{img.size}</td>
                    <td className="px-4 py-2 text-right">
                      <button
                        onClick={() => { setRunImage(`${img.repository}:${img.tag}`); setShowRun(true) }}
                        className="p-2 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded"
                        title="Run"
                      >
                        <Play className="w-4 h-4" />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  )
}
