'use client'

/**
 * Agent Card Component
 * Displays a single agent with status, actions, and metadata.
 */

import { useState, useEffect } from 'react'
import { formatDistanceToNow } from 'date-fns'
import { fr } from 'date-fns/locale/fr'
import { enUS } from 'date-fns/locale/en-US'
import {
  Play,
  Trash2,
  Loader2,
  ToggleLeft,
  ToggleRight,
  Globe,
  Search,
  Eye,
  Settings,
  CheckCircle2,
  XCircle,
  Clock,
} from 'lucide-react'
import { toast } from 'sonner'
import { useLanguage } from '@/lib/i18n'
import { getNotebookIcon } from '@/lib/notebook-icon'

// --- Types ---

interface AgentCardProps {
  agent: {
    id: string
    name: string
    description?: string | null
    type?: string | null
    isEnabled: boolean
    frequency: string
    lastRun: string | Date | null
    nextRun?: string | Date | null
    createdAt: string | Date
    updatedAt: string | Date
    _count: { actions: number }
    actions: { id: string; status: string; createdAt: string | Date }[]
    notebook?: { id: string; name: string; icon?: string | null } | null
  }
  onEdit: (id: string) => void
  onRefresh: () => void
  onToggle: (id: string, isEnabled: boolean) => void
}

// --- Config ---

const typeConfig: Record<string, { icon: typeof Globe; color: string; bgColor: string }> = {
  scraper: { icon: Globe, color: 'text-blue-600 dark:text-blue-400', bgColor: 'bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800' },
  researcher: { icon: Search, color: 'text-purple-600 dark:text-purple-400', bgColor: 'bg-purple-50 dark:bg-purple-950 border-purple-200 dark:border-purple-800' },
  monitor: { icon: Eye, color: 'text-amber-600 dark:text-amber-400', bgColor: 'bg-amber-50 dark:bg-amber-950 border-amber-200 dark:border-amber-800' },
  custom: { icon: Settings, color: 'text-green-600 dark:text-green-400', bgColor: 'bg-green-50 dark:bg-green-950 border-green-200 dark:border-green-800' },
}

const frequencyKeys: Record<string, string> = {
  manual: 'agents.frequencies.manual',
  hourly: 'agents.frequencies.hourly',
  daily: 'agents.frequencies.daily',
  weekly: 'agents.frequencies.weekly',
  monthly: 'agents.frequencies.monthly',
}

const statusKeys: Record<string, string> = {
  success: 'agents.status.success',
  failure: 'agents.status.failure',
  running: 'agents.status.running',
  pending: 'agents.status.pending',
}

// --- Component ---

export function AgentCard({ agent, onEdit, onRefresh, onToggle }: AgentCardProps) {
  const { t, language } = useLanguage()
  const [isRunning, setIsRunning] = useState(false)
  const [isDeleting, setIsDeleting] = useState(false)
  const [isToggling, setIsToggling] = useState(false)
  const [mounted, setMounted] = useState(false)

  // Prevent hydration mismatch for date formatting
  useEffect(() => { setMounted(true) }, [])

  const config = typeConfig[agent.type || 'scraper'] || typeConfig.custom
  const Icon = config.icon
  const lastAction = agent.actions[0]
  const dateLocale = language === 'fr' ? fr : enUS
  const isNew = new Date(agent.createdAt).getTime() === new Date(agent.updatedAt).getTime()

  const handleRun = async () => {
    setIsRunning(true)
    try {
      const { runAgent } = await import('@/app/actions/agent-actions')
      const result = await runAgent(agent.id)
      if (result.success) {
        toast.success(t('agents.toasts.runSuccess', { name: agent.name }))
      } else {
        toast.error(t('agents.toasts.runError', { error: result.error || t('agents.toasts.runFailed') }))
      }
    } catch {
      toast.error(t('agents.toasts.runGenericError'))
    } finally {
      setIsRunning(false)
      onRefresh()
    }
  }

  const handleDelete = async () => {
    if (!confirm(t('agents.actions.deleteConfirm', { name: agent.name }))) return
    setIsDeleting(true)
    try {
      const { deleteAgent } = await import('@/app/actions/agent-actions')
      await deleteAgent(agent.id)
      toast.success(t('agents.toasts.deleted', { name: agent.name }))
    } catch {
      toast.error(t('agents.toasts.deleteError'))
    } finally {
      setIsDeleting(false)
      onRefresh()
    }
  }

  const handleToggle = async () => {
    const newEnabled = !agent.isEnabled
    setIsToggling(true)
    onToggle(agent.id, newEnabled)
    try {
      const { toggleAgent } = await import('@/app/actions/agent-actions')
      await toggleAgent(agent.id, newEnabled)
      toast.success(newEnabled ? t('agents.actions.toggleOn') : t('agents.actions.toggleOff'))
    } catch {
      onToggle(agent.id, !newEnabled)
      toast.error(t('agents.toasts.toggleError'))
    } finally {
      setIsToggling(false)
    }
  }

  return (
    <div className={`
      bg-card rounded-xl border-2 transition-all overflow-hidden
      ${agent.isEnabled ? 'border-border hover:border-primary/30 hover:shadow-md' : 'border-border/50 opacity-60'}
    `}>
      <div className={`h-1 ${agent.isEnabled ? 'bg-primary' : 'bg-muted'}`} />

      <div className="p-4">
        <div className="flex items-start justify-between mb-3">
          <div className="flex items-center gap-3 min-w-0 flex-1">
            <div className={`p-2 rounded-lg border ${config.bgColor}`}>
              <Icon className={`w-4 h-4 ${config.color}`} />
            </div>
            <div className="min-w-0">
              <div className="flex items-center gap-2">
                <h3 className="font-semibold text-card-foreground truncate">{agent.name}</h3>
                {mounted && isNew && (
                  <span className="flex-shrink-0 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wider bg-emerald-100 dark:bg-emerald-900 text-emerald-700 dark:text-emerald-300 rounded">
                    {t('agents.newBadge')}
                  </span>
                )}
              </div>
              <span className={`text-xs font-medium ${config.color}`}>
                {t(`agents.types.${agent.type || 'custom'}`)}
              </span>
            </div>
          </div>
          <button onClick={handleToggle} disabled={isToggling} className="flex-shrink-0 ml-2 disabled:opacity-50 disabled:cursor-not-allowed">
            {agent.isEnabled ? (
              <ToggleRight className="w-6 h-6 text-primary" />
            ) : (
              <ToggleLeft className="w-6 h-6 text-muted-foreground/40" />
            )}
          </button>
        </div>

        {agent.description && (
          <p className="text-xs text-muted-foreground mb-3 line-clamp-2">{agent.description}</p>
        )}

        <div className="flex items-center gap-3 text-xs text-muted-foreground mb-3">
          <span className="flex items-center gap-1">
            <Clock className="w-3 h-3" />
            {t(frequencyKeys[agent.frequency] || 'agents.frequencies.manual')}
          </span>
          {agent.notebook && (
            <span className="flex items-center gap-1">
              {(() => {
                const Icon = getNotebookIcon(agent.notebook.icon)
                return <Icon className="w-3 h-3" />
              })()} {agent.notebook.name}
            </span>
          )}
          <span>{t('agents.metadata.executions', { count: agent._count.actions })}</span>
        </div>

        {agent.frequency !== 'manual' && agent.nextRun && new Date(agent.nextRun) > new Date() && (
          <div className="flex items-center gap-1.5 text-xs text-muted-foreground mb-3">
            <Clock className="w-3 h-3" />
            {t('agents.schedule.nextRun')}{' '}
            {mounted
              ? formatDistanceToNow(new Date(agent.nextRun), { addSuffix: true, locale: dateLocale })
              : new Date(agent.nextRun).toISOString().split('T')[0]}
          </div>
        )}

        {lastAction && (
          <div className={`
            flex items-center gap-1.5 text-xs px-2 py-1 rounded-md mb-3
            ${lastAction.status === 'success' ? 'bg-green-50 dark:bg-green-950 text-green-600 dark:text-green-400' : ''}
            ${lastAction.status === 'failure' ? 'bg-red-50 dark:bg-red-950 text-red-600 dark:text-red-400' : ''}
            ${lastAction.status === 'running' ? 'bg-blue-50 dark:bg-blue-950 text-blue-600 dark:text-blue-400' : ''}
          `}>
            {lastAction.status === 'success' && <CheckCircle2 className="w-3 h-3" />}
            {lastAction.status === 'failure' && <XCircle className="w-3 h-3" />}
            {lastAction.status === 'running' && <Loader2 className="w-3 h-3 animate-spin" />}
            {t(statusKeys[lastAction.status] || lastAction.status)}
            {' - '}
            {mounted
              ? formatDistanceToNow(new Date(lastAction.createdAt), { addSuffix: true, locale: dateLocale })
              : new Date(lastAction.createdAt).toISOString().split('T')[0]}
          </div>
        )}

        <div className="flex items-center gap-2">
          <button
            onClick={() => onEdit(agent.id)}
            className="flex-1 px-3 py-1.5 text-xs font-medium text-primary bg-primary/5 rounded-lg hover:bg-primary/10 transition-colors"
          >
            {t('agents.actions.edit')}
          </button>
          <button
            onClick={handleRun}
            disabled={isRunning || !agent.isEnabled}
            className="p-1.5 text-green-600 dark:text-green-400 bg-green-50 dark:bg-green-950 rounded-lg hover:bg-green-100 dark:hover:bg-green-900 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            title={t('agents.actions.run')}
          >
            {isRunning ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
          </button>
          <button
            onClick={handleDelete}
            disabled={isDeleting}
            className="p-1.5 text-red-500 dark:text-red-400 bg-red-50 dark:bg-red-950 rounded-lg hover:bg-red-100 dark:hover:bg-red-900 transition-colors disabled:opacity-50"
            title={t('agents.actions.delete')}
          >
            {isDeleting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
          </button>
        </div>
      </div>
    </div>
  )
}
