import { useEffect, useState } from 'react'
import { apiRequest, applyCrontab } from '../api/client'
import { Plus, Trash2, Edit2, Zap } from 'lucide-react'

interface CronJob {
  id: number
  name: string
  type: string
  schedule: string
  execstr: string
}

const SCHEDULE_PRESETS = [
  { label: 'Every minute', value: '* * * * *' },
  { label: 'Every 5 min', value: '*/5 * * * *' },
  { label: 'Every hour', value: '0 * * * *' },
  { label: 'Daily', value: '0 0 * * *' },
  { label: 'Weekly', value: '0 0 * * 0' },
]

export function CrontabPage() {
  const [jobs, setJobs] = useState<CronJob[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [showForm, setShowForm] = useState(false)
  const [editingId, setEditingId] = useState<number | null>(null)
  const [editJob, setEditJob] = useState<CronJob | null>(null)
  const [saving, setSaving] = useState(false)
  const [formError, setFormError] = useState('')
  const [applying, setApplying] = useState(false)

  const loadJobs = () => {
    setLoading(true)
    apiRequest<CronJob[]>('/crontab/list')
      .then(setJobs)
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false))
  }

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

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    const form = e.currentTarget
    const name = (form.elements.namedItem('name') as HTMLInputElement).value.trim()
    const schedule = (form.elements.namedItem('schedule') as HTMLInputElement).value.trim()
    const execstr = (form.elements.namedItem('execstr') as HTMLTextAreaElement).value.trim()

    if (!schedule || !execstr) {
      setFormError('Schedule and command are required')
      return
    }
    setSaving(true)
    setFormError('')
    const body = { name, type: 'shell', schedule, execstr }
    const promise = editingId
      ? apiRequest(`/crontab/${editingId}`, { method: 'PUT', body: JSON.stringify(body) })
      : apiRequest('/crontab/create', { method: 'POST', body: JSON.stringify(body) })
    promise
      .then(() => {
        setShowForm(false)
        setEditingId(null)
        form.reset()
        loadJobs()
      })
      .catch((err) => setFormError(err.message))
      .finally(() => setSaving(false))
  }

  const handleEdit = (job: CronJob) => {
    setEditingId(job.id)
    setEditJob(job)
    setShowForm(true)
  }

  const handleDelete = (id: number) => {
    if (!confirm('Delete this cron job?')) return
    apiRequest(`/crontab/${id}`, { method: 'DELETE' })
      .then(loadJobs)
      .catch((err) => setError(err.message))
  }

  const handleApply = () => {
    setApplying(true)
    applyCrontab()
      .then(loadJobs)
      .catch((err) => setError(err.message))
      .finally(() => setApplying(false))
  }

  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">Cron</h1>
        <div className="flex gap-2">
          <button
            onClick={handleApply}
            disabled={applying || jobs.length === 0}
            className="flex items-center gap-2 px-4 py-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-400 text-white rounded-lg font-medium"
          >
            <Zap className="w-4 h-4" />
            {applying ? 'Applying...' : 'Apply to System'}
          </button>
          <button
            onClick={() => {
              setEditingId(null)
              setEditJob(null)
              setShowForm(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 Cron
          </button>
        </div>
      </div>

      {showForm && (
        <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-lg">
            <h2 className="text-xl font-bold mb-4 text-gray-800 dark:text-white">
              {editingId ? 'Edit Cron Job' : 'Create Cron Job'}
            </h2>
            <form key={editingId ?? 'new'} onSubmit={handleSubmit} className="space-y-4">
              {formError && (
                <div className="p-2 rounded bg-red-100 dark:bg-red-900/30 text-red-700 text-sm">{formError}</div>
              )}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Name (optional)</label>
                <input id="cron-name" name="name" type="text" placeholder="My task" defaultValue={editJob?.name} className="w-full px-4 py-2 border 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">Schedule (cron)</label>
                <select
                  className="w-full mb-2 px-4 py-2 border rounded-lg bg-white dark:bg-gray-700"
                  onChange={(e) => {
                    const v = e.target.value
                    if (v) (document.getElementById('cron-schedule') as HTMLInputElement).value = v
                  }}
                >
                  <option value="">Select preset...</option>
                  {SCHEDULE_PRESETS.map((p) => (
                    <option key={p.value} value={p.value}>{p.label} ({p.value})</option>
                  ))}
                </select>
                <input id="cron-schedule" name="schedule" type="text" placeholder="* * * * *" defaultValue={editJob?.schedule} className="w-full px-4 py-2 border 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">Command</label>
                <textarea id="cron-execstr" name="execstr" rows={3} placeholder="/usr/bin/php /www/wwwroot/script.php" defaultValue={editJob?.execstr} className="w-full px-4 py-2 border rounded-lg bg-white dark:bg-gray-700" required />
              </div>
              <div className="flex gap-2 justify-end pt-2">
                <button type="button" onClick={() => { setShowForm(false); setEditingId(null); setEditJob(null) }} className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg">Cancel</button>
                <button type="submit" disabled={saving} className="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white rounded-lg font-medium">
                  {saving ? 'Saving...' : editingId ? 'Update' : 'Create'}
                </button>
              </div>
            </form>
          </div>
        </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">
        Jobs are stored in the panel. Click &quot;Apply to System&quot; to sync them to the system crontab (root).
      </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">Name</th>
              <th className="px-4 py-2 text-left text-sm font-medium text-gray-700 dark:text-gray-300">Schedule</th>
              <th className="px-4 py-2 text-left text-sm font-medium text-gray-700 dark:text-gray-300">Command</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">
            {jobs.length === 0 ? (
              <tr>
                <td colSpan={4} className="px-4 py-8 text-center text-gray-500">No cron jobs. Click "Add Cron" to create one.</td>
              </tr>
            ) : (
              jobs.map((j) => (
                <tr key={j.id}>
                  <td className="px-4 py-2 text-gray-900 dark:text-white">{j.name || '-'}</td>
                  <td className="px-4 py-2 text-gray-600 dark:text-gray-400 font-mono text-sm">{j.schedule}</td>
                  <td className="px-4 py-2 text-gray-600 dark:text-gray-400 font-mono text-sm max-w-md truncate">{j.execstr}</td>
                  <td className="px-4 py-2 text-right flex gap-1 justify-end">
                    <button onClick={() => handleEdit(j)} className="p-2 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded" title="Edit"><Edit2 className="w-4 h-4" /></button>
                    <button onClick={() => handleDelete(j.id)} className="p-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded" title="Delete"><Trash2 className="w-4 h-4" /></button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
