'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
    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', bgColor: 'bg-blue-50 border-blue-200' },
  researcher: { icon: Search, color: 'text-purple-600', bgColor: 'bg-purple-50 border-purple-200' },
  monitor: { icon: Eye, color: 'text-amber-600', bgColor: 'bg-amber-50 border-amber-200' },
  custom: { icon: Settings, color: 'text-green-600', bgColor: 'bg-green-50 border-green-200' },
}

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-white rounded-xl border-2 transition-all overflow-hidden
      ${agent.isEnabled ? 'border-slate-200 hover:border-primary/30 hover:shadow-md' : 'border-slate-100 opacity-60'}
    `}>
      <div className={`h-1 ${agent.isEnabled ? 'bg-primary' : 'bg-slate-200'}`} />

      <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-slate-800 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 text-emerald-700 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-slate-300" />
            )}
          </button>
        </div>

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

        <div className="flex items-center gap-3 text-xs text-slate-400 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>

        {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 text-green-600' : ''}
            ${lastAction.status === 'failure' ? 'bg-red-50 text-red-600' : ''}
            ${lastAction.status === 'running' ? 'bg-blue-50 text-blue-600' : ''}
          `}>
            {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 bg-green-50 rounded-lg hover:bg-green-100 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 bg-red-50 rounded-lg hover:bg-red-100 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>
  )
}
