'use client'

import { useCallback, useEffect, useState } from 'react'
import {
  cancelAgentTask,
  getAgentFeed,
  getPlatformApprovals,
  getSystemStatus,
  setBlockedTools,
  setBusinessAgents,
  setGlobalAgents,
  SystemStatus,
  AgentFeed,
  PlatformApproval,
} from '@/lib/api/platform'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card'
import { Skeleton } from '@/components/ui/Skeleton'
import { ErrorState } from '@/components/ui/ErrorState'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { useToast } from '@/components/ui/Toast'
import { AlertTriangle, Ban, Bot, CheckCircle2, ShieldCheck, XCircle } from 'lucide-react'
import { cn } from '@/lib/utils'

type TaskStatus = 'created' | 'running' | 'awaiting_approval'

function isCancellable(status: string): boolean {
  return status === 'created' || status === 'running' || status === 'awaiting_approval'
}

function statusPill(status: string) {
  const base =
    'inline-flex rounded-full px-2 py-0.5 text-xs font-semibold uppercase tracking-wide'
  const color =
    status === 'completed'
      ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300'
      : status === 'failed' || status === 'cancelled'
        ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'
        : status === 'running'
          ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300'
          : 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300'
  return <span className={cn(base, color)}>{status}</span>
}

export default function AgentControlPage() {
  const { toast } = useToast()
  const [status, setStatus] = useState<SystemStatus | null>(null)
  const [feed, setFeed] = useState<AgentFeed | null>(null)
  const [approvals, setApprovals] = useState<PlatformApproval[]>([])
  const [error, setError] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)

  const [pauseReason, setPauseReason] = useState('')
  const [blocked, setBlocked] = useState<string[]>([])
  const [selectedBlocked, setSelectedBlocked] = useState<string[]>([])

  const load = useCallback(() => {
    setError(null)
    getSystemStatus().then(res => {
      if (res.success) {
        setStatus(res.data)
        setPauseReason(res.data.agents_pause_reason)
        setBlocked(res.data.blocked_tools)
        setSelectedBlocked(res.data.blocked_tools)
      } else setError(res.message)
    })
    getAgentFeed({ limit: 50 }).then(res => {
      if (res.success) setFeed(res.data)
    })
    getPlatformApprovals().then(res => {
      if (res.success) setApprovals(res.data.approvals)
    })
  }, [])

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

  const handleToggleGlobal = async () => {
    setBusy(true)
    const res = await setGlobalAgents(!(status?.agents_enabled ?? true), pauseReason)
    setBusy(false)
    if (res.success) {
      toast({
        title: 'Agent control updated',
        description: res.data.enabled
          ? 'Agents are now running across all businesses.'
          : 'Agents are paused globally.',
        variant: res.data.enabled ? 'success' : 'info',
      })
      load()
    } else {
      toast({ title: 'Update failed', description: res.message, variant: 'destructive' })
    }
  }

  const handleResumeBusiness = async (businessId: string, name: string) => {
    const res = await setBusinessAgents(businessId, true)
    if (res.success) {
      toast({ title: `${name} agents resumed`, variant: 'success' })
      load()
    } else {
      toast({ title: 'Resume failed', description: res.message, variant: 'destructive' })
    }
  }

  const handleSaveBlocked = async () => {
    setBusy(true)
    const res = await setBlockedTools(selectedBlocked)
    setBusy(false)
    if (res.success) {
      setBlocked(res.data.blocked_tools)
      toast({ title: 'Blocked tools updated', variant: 'success' })
    } else {
      toast({ title: 'Update failed', description: res.message, variant: 'destructive' })
    }
  }

  const handleCancel = async (taskId: string) => {
    const res = await cancelAgentTask(taskId)
    if (res.success) {
      toast({ title: 'Task cancelled', variant: 'success' })
      load()
    } else {
      toast({ title: 'Cancel failed', description: res.message, variant: 'destructive' })
    }
  }

  if (error && !status) return <ErrorState message={error} />
  if (!status) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-10 w-72" />
        <Skeleton className="h-32 w-full" />
        <Skeleton className="h-64 w-full" />
      </div>
    )
  }

  const globalEnabled = status.agents_enabled

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Agent Control</h1>
        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
          Whole-system operator controls: the agents kill-switch, per-business pauses,
          blocked tools, the live agent feed and cross-tenant approvals. Everything here is audited.
        </p>
      </div>

      {/* Kill switch */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-lg">
            <Bot className="h-5 w-5 text-indigo-600 dark:text-indigo-400" /> Global agents
            {globalEnabled ? (
              <span className="ml-auto inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2.5 py-0.5 text-xs font-semibold text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300">
                <CheckCircle2 className="h-3.5 w-3.5" /> Running
              </span>
            ) : (
              <span className="ml-auto inline-flex items-center gap-1 rounded-full bg-red-100 px-2.5 py-0.5 text-xs font-semibold text-red-700 dark:bg-red-900/40 dark:text-red-300">
                <AlertTriangle className="h-3.5 w-3.5" /> Paused
              </span>
            )}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-gray-600 dark:text-gray-300">
            {globalEnabled
              ? 'Order-created and restock agents may run for every business. In-flight tasks continue; new task runs and scheduled jobs are gated while paused.'
              : `Agents are paused platform-wide${status.agents_pause_reason ? ` — ${status.agents_pause_reason}` : ''}. Skipped runs are audited, never dropped.`}
          </p>
          {!globalEnabled && (
            <div className="mt-4 flex flex-col gap-2 sm:flex-row sm:items-center">
              <label htmlFor="pause-reason" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Reason
              </label>
              <Input
                id="pause-reason"
                value={pauseReason}
                onChange={e => setPauseReason(e.target.value)}
                placeholder="Visible in the audit trail"
                className="sm:max-w-md"
              />
            </div>
          )}
          <div className="mt-4 flex flex-wrap gap-3">
            <Button variant={globalEnabled ? 'danger' : 'primary'} onClick={handleToggleGlobal} loading={busy}>
              {globalEnabled ? (
                <>
                  <Ban className="h-4 w-4" /> Pause all agents
                </>
              ) : (
                <>
                  <CheckCircle2 className="h-4 w-4" /> Resume all agents
                </>
              )}
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Paused businesses + blocked tools */}
      <div className="grid gap-6 lg:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Businesses with agents paused</CardTitle>
          </CardHeader>
          <CardContent>
            {status.paused_businesses.length === 0 ? (
              <p className="text-sm text-gray-500">No per-business pauses. Agents run everywhere.</p>
            ) : (
              <ul className="divide-y divide-gray-200 dark:divide-gray-700">
                {status.paused_businesses.map(b => (
                  <li key={b.id} className="flex items-center justify-between gap-3 py-2.5">
                    <div className="min-w-0">
                      <p className="font-medium text-gray-900 dark:text-white">{b.name}</p>
                      <p className="truncate text-xs text-gray-500">{b.id}</p>
                    </div>
                    <Button size="sm" variant="outline" onClick={() => handleResumeBusiness(b.id, b.name)}>
                      Resume
                    </Button>
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-lg">
              <ShieldCheck className="h-5 w-5 text-indigo-600 dark:text-indigo-400" /> Blocked agent tools
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm text-gray-600 dark:text-gray-300">
              Tools checked here are refused whenever the supervisor tries to call them (e.g. a paused
              customer-notification). Changing these takes effect on the next run.
            </p>
            <div className="mt-3 grid gap-1.5 sm:grid-cols-2">
              {status.available_tools.map(tool => (
                <label
                  key={tool}
                  className="flex items-center gap-2 rounded-lg border border-gray-200 px-3 py-2 text-sm dark:border-gray-700"
                >
                  <input
                    type="checkbox"
                    className="h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                    checked={selectedBlocked.includes(tool)}
                    onChange={e => {
                      setSelectedBlocked(prev =>
                        e.target.checked ? [...prev, tool] : prev.filter(t => t !== tool)
                      )
                    }}
                  />
                  <span className="font-medium">{tool}</span>
                  {blocked.includes(tool) && (
                    <span className="ml-auto text-[10px] font-semibold uppercase tracking-wide text-red-600 dark:text-red-400">
                      blocked
                    </span>
                  )}
                </label>
              ))}
            </div>
            <div className="mt-4">
              <Button onClick={handleSaveBlocked} loading={busy}>
                Save blocked tools
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Approvals (see-only) */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-lg">
            <XCircle className="h-5 w-5 text-indigo-600 dark:text-indigo-400" /> Cross-tenant approvals
            <span className="ml-auto rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-semibold text-gray-600 dark:bg-gray-800 dark:text-gray-300">
              view only
            </span>
          </CardTitle>
        </CardHeader>
        <CardContent>
          {approvals.length === 0 ? (
            <p className="text-sm text-gray-500">No approvals pending across any business.</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-left text-sm">
                <thead className="text-xs uppercase tracking-wide text-gray-500">
                  <tr>
                    <th className="py-2 pr-3">Business</th>
                    <th className="py-2 pr-3">Action</th>
                    <th className="py-2 pr-3">Amount</th>
                    <th className="py-2 pr-3">Status</th>
                    <th className="py-2">Description</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                  {approvals.map(a => (
                    <tr key={a.id}>
                      <td className="py-2.5 pr-3 font-medium text-gray-900 dark:text-white">
                        {a.business_name || a.business_id}
                      </td>
                      <td className="py-2.5 pr-3">{a.action_type.replace(/_/g, ' ')}</td>
                      <td className="py-2.5 pr-3">
                        {a.amount != null
                          ? a.amount.toLocaleString(undefined, {
                              minimumFractionDigits: 2,
                              maximumFractionDigits: 2,
                            })
                          : '—'}
                      </td>
                      <td className="py-2.5 pr-3">{statusPill(a.status)}</td>
                      <td className="py-2.5 text-gray-500">
                        {a.description || a.title || '—'}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Agent feed */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Live agent feed</CardTitle>
        </CardHeader>
        <CardContent>
          {!feed || feed.tasks.length === 0 ? (
            <p className="text-sm text-gray-500">No agent tasks recorded yet.</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-left text-sm">
                <thead className="text-xs uppercase tracking-wide text-gray-500">
                  <tr>
                    <th className="py-2 pr-3">Business</th>
                    <th className="py-2 pr-3">Type</th>
                    <th className="py-2 pr-3">Status</th>
                    <th className="py-2 pr-3">Started</th>
                    <th className="py-2">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                  {feed.tasks.map(task => (
                    <tr key={task.id}>
                      <td className="py-2.5 pr-3 font-medium text-gray-900 dark:text-white">
                        {task.business_name || task.business_id}
                      </td>
                      <td className="py-2.5 pr-3">{task.task_type}</td>
                      <td className="py-2.5 pr-3">{statusPill(task.status)}</td>
                      <td className="py-2.5 pr-3 text-gray-500">
                        {task.started_at ? new Date(task.started_at).toLocaleString() : '—'}
                      </td>
                      <td className="py-2.5">
                        {isCancellable(task.status) && (
                          <Button
                            size="sm"
                            variant="danger"
                            onClick={() => handleCancel(task.id)}
                            disabled={busy}
                          >
                            Cancel
                          </Button>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}