'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Clock,
  Play,
  Pause,
  Settings,
  ChevronDown,
  ChevronUp,
  AlertCircle,
  CheckCircle,
  XCircle,
  Bell,
  Shield,
  DollarSign,
  TrendingUp,
  Package,
  Database,
  Users,
  BarChart,
} from 'lucide-react';

interface SystemTask {
  id: string;
  taskKey: string;
  name: string;
  description: string | null;
  category: string;
  schedule: string | null;
  isEnabled: boolean;
  isDefaultEnabled: boolean;
  isCritical: boolean;
  lastRunAt: Date | null;
  lastRunStatus: string | null;
  lastRunDuration: number | null;
  runCount: number;
  failCount: number;
  _count: { runs: number; subscriptions: number };
}

interface Props {
  tasksByCategory: Record<string, SystemTask[]>;
}

const categoryIcons: Record<string, React.ReactNode> = {
  finance: <DollarSign className="w-5 h-5" />,
  security: <Shield className="w-5 h-5" />,
  marketing: <TrendingUp className="w-5 h-5" />,
  operations: <Package className="w-5 h-5" />,
  data: <Database className="w-5 h-5" />,
  hr: <Users className="w-5 h-5" />,
  executive: <BarChart className="w-5 h-5" />,
};

const categoryColors: Record<string, string> = {
  finance: 'text-green-400 bg-green-400/10',
  security: 'text-red-400 bg-red-400/10',
  marketing: 'text-blue-400 bg-blue-400/10',
  operations: 'text-orange-400 bg-orange-400/10',
  data: 'text-brand-secondary-light bg-brand-secondary-light/10',
  hr: 'text-pink-400 bg-pink-400/10',
  executive: 'text-brand bg-brand/10',
};

export function TaskManagementPanel({ tasksByCategory }: Props) {
  const [expandedCategories, setExpandedCategories] = useState<Set<string>>(
    new Set(Object.keys(tasksByCategory))
  );
  const [loadingTasks, setLoadingTasks] = useState<Set<string>>(new Set());
  const [taskStates, setTaskStates] = useState<Record<string, boolean>>(
    Object.values(tasksByCategory)
      .flat()
      .reduce((acc, task) => ({ ...acc, [task.id]: task.isEnabled }), {})
  );

  const toggleCategory = (category: string) => {
    setExpandedCategories((prev) => {
      const next = new Set(prev);
      if (next.has(category)) {
        next.delete(category);
      } else {
        next.add(category);
      }
      return next;
    });
  };

  const toggleTask = async (task: SystemTask) => {
    if (task.isCritical && taskStates[task.id]) {
      alert('Critical tasks cannot be disabled');
      return;
    }

    setLoadingTasks((prev) => new Set([...prev, task.id]));

    try {
      const response = await fetch(`/api/autonomy/tasks/${task.taskKey}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ isEnabled: !taskStates[task.id] }),
      });

      if (response.ok) {
        setTaskStates((prev) => ({ ...prev, [task.id]: !prev[task.id] }));
      }
    } catch (error) {
      console.error('Failed to toggle task:', error);
    } finally {
      setLoadingTasks((prev) => {
        const next = new Set(prev);
        next.delete(task.id);
        return next;
      });
    }
  };

  const triggerTask = async (task: SystemTask) => {
    setLoadingTasks((prev) => new Set([...prev, task.id]));

    try {
      const response = await fetch(`/api/autonomy/tasks/${task.taskKey}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({}),
      });

      if (response.ok) {
        // Refresh the page to show updated run info
        window.location.reload();
      }
    } catch (error) {
      console.error('Failed to trigger task:', error);
    } finally {
      setLoadingTasks((prev) => {
        const next = new Set(prev);
        next.delete(task.id);
        return next;
      });
    }
  };

  const formatSchedule = (schedule: string | null) => {
    if (!schedule) return 'Not scheduled';
    // Simple cron to human readable
    if (schedule.startsWith('*/15')) return 'Every 15 minutes';
    if (schedule.includes('* * *') && schedule.startsWith('0 ')) {
      const hour = schedule.split(' ')[1];
      return `Daily at ${hour}:00`;
    }
    if (schedule.includes('* * 1')) return 'Weekly (Monday)';
    if (schedule.includes('1 * *')) return 'Monthly (1st)';
    return schedule;
  };

  const formatDuration = (ms: number | null) => {
    if (!ms) return '-';
    if (ms < 1000) return `${ms}ms`;
    if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
    return `${(ms / 60000).toFixed(1)}m`;
  };

  const formatDate = (date: Date | null) => {
    if (!date) return 'Never';
    return new Date(date).toLocaleString();
  };

  return (
    <div className="space-y-6">
      {Object.entries(tasksByCategory).map(([category, tasks]) => (
        <div key={category} className="glass-card overflow-hidden">
          {/* Category Header */}
          <button
            onClick={() => toggleCategory(category)}
            className={`w-full p-4 flex items-center justify-between ${categoryColors[category]} hover:bg-white/5 transition-colors`}
          >
            <div className="flex items-center gap-3">
              {categoryIcons[category]}
              <span className="text-lg font-semibold capitalize">{category}</span>
              <span className="text-sm text-gray-400">
                ({tasks.filter((t) => taskStates[t.id]).length}/{tasks.length} enabled)
              </span>
            </div>
            {expandedCategories.has(category) ? (
              <ChevronUp className="w-5 h-5" />
            ) : (
              <ChevronDown className="w-5 h-5" />
            )}
          </button>

          {/* Tasks List */}
          <AnimatePresence>
            {expandedCategories.has(category) && (
              <motion.div
                initial={{ height: 0, opacity: 0 }}
                animate={{ height: 'auto', opacity: 1 }}
                exit={{ height: 0, opacity: 0 }}
                transition={{ duration: 0.2 }}
              >
                <div className="divide-y divide-white/10">
                  {tasks.map((task) => (
                    <div
                      key={task.id}
                      className="p-4 hover:bg-white/5 transition-colors"
                    >
                      <div className="flex items-start justify-between gap-4">
                        {/* Task Info */}
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <h3 className="font-medium">{task.name}</h3>
                            {task.isCritical && (
                              <span className="px-2 py-0.5 text-xs bg-red-500/20 text-red-400 rounded">
                                CRITICAL
                              </span>
                            )}
                            {task.isDefaultEnabled && (
                              <span className="px-2 py-0.5 text-xs bg-brand-deep/20 text-brand rounded">
                                DEFAULT
                              </span>
                            )}
                          </div>
                          <p className="text-sm text-gray-400 mt-1">
                            {task.description}
                          </p>
                          <div className="flex items-center gap-4 mt-2 text-xs text-gray-500">
                            <span className="flex items-center gap-1">
                              <Clock className="w-3 h-3" />
                              {formatSchedule(task.schedule)}
                            </span>
                            <span className="flex items-center gap-1">
                              <Bell className="w-3 h-3" />
                              {task._count.subscriptions} subscribers
                            </span>
                            <span>
                              Runs: {task.runCount} | Failed: {task.failCount}
                            </span>
                          </div>
                        </div>

                        {/* Last Run Status */}
                        <div className="text-right text-sm">
                          <div className="flex items-center gap-2 justify-end">
                            {task.lastRunStatus === 'success' && (
                              <CheckCircle className="w-4 h-4 text-green-400" />
                            )}
                            {task.lastRunStatus === 'failed' && (
                              <XCircle className="w-4 h-4 text-red-400" />
                            )}
                            {task.lastRunStatus === 'running' && (
                              <AlertCircle className="w-4 h-4 text-yellow-400 animate-pulse" />
                            )}
                            <span className="text-gray-400">
                              {formatDate(task.lastRunAt)}
                            </span>
                          </div>
                          <span className="text-gray-500">
                            Duration: {formatDuration(task.lastRunDuration)}
                          </span>
                        </div>

                        {/* Actions */}
                        <div className="flex items-center gap-2">
                          <button
                            onClick={() => triggerTask(task)}
                            disabled={loadingTasks.has(task.id) || !taskStates[task.id]}
                            className="p-2 rounded-lg bg-white/5 hover:bg-white/10 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                            title="Run now"
                          >
                            <Play className="w-4 h-4 text-brand" />
                          </button>

                          <button
                            onClick={() => toggleTask(task)}
                            disabled={loadingTasks.has(task.id)}
                            className={`p-2 rounded-lg transition-colors ${
                              taskStates[task.id]
                                ? 'bg-green-500/20 hover:bg-green-500/30'
                                : 'bg-white/5 hover:bg-white/10'
                            }`}
                            title={taskStates[task.id] ? 'Disable' : 'Enable'}
                          >
                            {taskStates[task.id] ? (
                              <Pause className="w-4 h-4 text-green-400" />
                            ) : (
                              <Play className="w-4 h-4 text-gray-400" />
                            )}
                          </button>

                          <button
                            className="p-2 rounded-lg bg-white/5 hover:bg-white/10 transition-colors"
                            title="Settings"
                          >
                            <Settings className="w-4 h-4 text-gray-400" />
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      ))}
    </div>
  );
}
