import React, { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from '../api/client';
import {
  Plus,
  Play,
  Pause,
  Trash2,
  Edit,
  Clock,
  Calendar,
  CalendarDays,
  RotateCw,
  CheckCircle2,
  XCircle,
  AlertCircle,
  Zap,
  Power,
} from 'lucide-react';
import toast from 'react-hot-toast';
import CreateTaskModal from '../components/CreateTaskModal';
import EditTaskModal from '../components/EditTaskModal';
import { usePlanFeatures } from '../hooks/usePlanFeatures';
import { LockedSection } from '../components/UpgradePrompt';

// Types
interface ScheduledTask {
  id: string;
  name: string;
  description: string;
  plugin_name: string;
  plugin_display_name: string;
  schedule_type: 'ONE_TIME' | 'INTERVAL' | 'CRON';
  cron_expression?: string;
  interval_minutes?: number;
  run_at?: string;
  next_run_at?: string;
  last_run_at?: string;
  status: 'ACTIVE' | 'PAUSED' | 'DISABLED';
  last_run_status?: string;
  plugin_config: Record<string, any>;
  created_at: string;
  updated_at: string;
}

interface PluginInstallation {
  id: string;
  template: number;
  template_name: string;
  template_slug: string;
  template_description: string;
  category: string;
  version: string;
  author_name: string;
  logo_url?: string;
  template_variables: Record<string, any>;
  scheduled_task?: number;
  scheduled_task_name?: string;
  installed_at: string;
  config_values: Record<string, any>;
  has_update: boolean;
}

interface GlobalEventPlugin {
  id: string;
  plugin_installation: number;
  plugin_name: string;
  plugin_description: string;
  plugin_category: string;
  plugin_logo_url?: string;
  trigger: string;
  trigger_display: string;
  offset_minutes: number;
  timing_description: string;
  is_active: boolean;
  apply_to_existing: boolean;
  execution_order: number;
  events_count: number;
  created_at: string;
  updated_at: string;
}

// Unified task type for display
type UnifiedTask = {
  type: 'scheduled';
  data: ScheduledTask;
} | {
  type: 'event';
  data: GlobalEventPlugin;
};

const Tasks: React.FC = () => {
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editingTask, setEditingTask] = useState<ScheduledTask | null>(null);
  const [editingEventAutomation, setEditingEventAutomation] = useState<GlobalEventPlugin | null>(null);

  // Check plan permissions - tasks requires both plugins AND tasks features
  const { canUse, isLoading: permissionsLoading } = usePlanFeatures();
  const hasPluginsFeature = canUse('plugins');
  const hasTasksFeature = canUse('tasks');
  const isLocked = !hasPluginsFeature || !hasTasksFeature;

  // Fetch scheduled tasks
  const { data: scheduledTasks = [], isLoading: tasksLoading } = useQuery<ScheduledTask[]>({
    queryKey: ['scheduled-tasks'],
    queryFn: async () => {
      const { data } = await axios.get('/scheduled-tasks/');
      return data;
    },
  });

  // Fetch global event plugins (event automations)
  const { data: eventAutomations = [], isLoading: automationsLoading } = useQuery<GlobalEventPlugin[]>({
    queryKey: ['global-event-plugins'],
    queryFn: async () => {
      const { data } = await axios.get('/global-event-plugins/');
      return data;
    },
  });

  // Combine into unified list
  const allTasks: UnifiedTask[] = useMemo(() => {
    const scheduled: UnifiedTask[] = scheduledTasks.map(t => ({ type: 'scheduled' as const, data: t }));
    const events: UnifiedTask[] = eventAutomations.map(e => ({ type: 'event' as const, data: e }));
    return [...scheduled, ...events].sort((a, b) => {
      const dateA = new Date(a.data.created_at).getTime();
      const dateB = new Date(b.data.created_at).getTime();
      return dateB - dateA; // Most recent first
    });
  }, [scheduledTasks, eventAutomations]);

  const isLoading = tasksLoading || automationsLoading;

  // Delete task
  const deleteMutation = useMutation({
    mutationFn: async (taskId: string) => {
      await axios.delete(`/scheduled-tasks/${taskId}/`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scheduled-tasks'] });
      toast.success('Task deleted successfully');
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to delete task');
    },
  });

  // Toggle task active status
  const toggleActiveMutation = useMutation({
    mutationFn: async ({ taskId, status }: { taskId: string; status: 'ACTIVE' | 'PAUSED' }) => {
      await axios.patch(`/scheduled-tasks/${taskId}/`, { status });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scheduled-tasks'] });
      toast.success('Task updated successfully');
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to update task');
    },
  });

  // Trigger task manually
  const triggerMutation = useMutation({
    mutationFn: async (taskId: string) => {
      await axios.post(`/scheduled-tasks/${taskId}/trigger/`);
    },
    onSuccess: () => {
      toast.success('Task triggered successfully');
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to trigger task');
    },
  });

  // Delete event automation
  const deleteEventAutomationMutation = useMutation({
    mutationFn: async (automationId: string) => {
      await axios.delete(`/global-event-plugins/${automationId}/`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['global-event-plugins'] });
      toast.success('Event automation deleted');
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to delete automation');
    },
  });

  // Toggle event automation active status
  const toggleEventAutomationMutation = useMutation({
    mutationFn: async (automationId: string) => {
      await axios.post(`/global-event-plugins/${automationId}/toggle/`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['global-event-plugins'] });
      toast.success('Automation updated');
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to update automation');
    },
  });

  // Update event automation
  const updateEventAutomationMutation = useMutation({
    mutationFn: async ({ id, data }: { id: string; data: Partial<GlobalEventPlugin> }) => {
      await axios.patch(`/global-event-plugins/${id}/`, data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['global-event-plugins'] });
      toast.success('Automation updated');
      setEditingEventAutomation(null);
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to update automation');
    },
  });

  const getScheduleDisplay = (task: ScheduledTask): string => {
    if (task.schedule_type === 'ONE_TIME') {
      return `Once on ${new Date(task.run_at!).toLocaleString()}`;
    } else if (task.schedule_type === 'INTERVAL') {
      const hours = Math.floor(task.interval_minutes! / 60);
      const mins = task.interval_minutes! % 60;
      if (hours > 0 && mins > 0) {
        return `Every ${hours}h ${mins}m`;
      } else if (hours > 0) {
        return `Every ${hours} hour${hours > 1 ? 's' : ''}`;
      } else {
        return `Every ${mins} minute${mins > 1 ? 's' : ''}`;
      }
    } else {
      return task.cron_expression || 'Custom schedule';
    }
  };

  const getScheduleIcon = (task: ScheduledTask) => {
    if (task.schedule_type === 'ONE_TIME') return Calendar;
    if (task.schedule_type === 'INTERVAL') return RotateCw;
    return Clock;
  };

  const getStatusColor = (task: ScheduledTask): string => {
    if (task.status === 'PAUSED' || task.status === 'DISABLED') return 'text-gray-400 dark:text-gray-500';
    if (task.last_run_at) return 'text-green-600 dark:text-green-400';
    return 'text-blue-600 dark:text-blue-400';
  };

  const getStatusIcon = (task: ScheduledTask) => {
    if (task.status === 'PAUSED' || task.status === 'DISABLED') return Pause;
    if (task.last_run_at) return CheckCircle2;
    return AlertCircle;
  };

  if (isLoading || permissionsLoading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  return (
    <LockedSection feature="tasks" isLocked={isLocked} variant="overlay">
    <div className="p-6 max-w-7xl mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
            {t('Tasks')}
          </h1>
          <p className="text-gray-600 dark:text-gray-400 mt-1">
            Schedule and manage automated plugin executions
          </p>
        </div>
        <button
          onClick={() => setShowCreateModal(true)}
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
        >
          <Plus className="w-5 h-5" />
          New Task
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <div className="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
              <Zap className="w-5 h-5 text-blue-600 dark:text-blue-400" />
            </div>
            <div>
              <p className="text-sm text-gray-600 dark:text-gray-400">Total Tasks</p>
              <p className="text-2xl font-bold text-gray-900 dark:text-white">{allTasks.length}</p>
            </div>
          </div>
        </div>

        <div className="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-green-100 dark:bg-green-900/30 rounded-lg">
              <CheckCircle2 className="w-5 h-5 text-green-600 dark:text-green-400" />
            </div>
            <div>
              <p className="text-sm text-gray-600 dark:text-gray-400">Active</p>
              <p className="text-2xl font-bold text-gray-900 dark:text-white">
                {scheduledTasks.filter(t => t.status === 'ACTIVE').length + eventAutomations.filter(e => e.is_active).length}
              </p>
            </div>
          </div>
        </div>

        <div className="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-purple-100 dark:bg-purple-900/30 rounded-lg">
              <CalendarDays className="w-5 h-5 text-purple-600 dark:text-purple-400" />
            </div>
            <div>
              <p className="text-sm text-gray-600 dark:text-gray-400">Event Automations</p>
              <p className="text-2xl font-bold text-gray-900 dark:text-white">
                {eventAutomations.length}
              </p>
            </div>
          </div>
        </div>

        <div className="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
              <RotateCw className="w-5 h-5 text-blue-600 dark:text-blue-400" />
            </div>
            <div>
              <p className="text-sm text-gray-600 dark:text-gray-400">Scheduled</p>
              <p className="text-2xl font-bold text-gray-900 dark:text-white">
                {scheduledTasks.length}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Tasks List */}
      {allTasks.length === 0 ? (
        <div className="text-center py-16 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
          <Zap className="w-16 h-16 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
            No tasks yet
          </h3>
          <p className="text-gray-600 dark:text-gray-400 mb-4">
            Create your first automated task to get started
          </p>
          <button
            onClick={() => setShowCreateModal(true)}
            className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Plus className="w-5 h-5" />
            Create Task
          </button>
        </div>
      ) : (
        <div className="space-y-4">
          {allTasks.map((unifiedTask) => {
            if (unifiedTask.type === 'scheduled') {
              const task = unifiedTask.data;
              const ScheduleIcon = getScheduleIcon(task);
              const StatusIcon = getStatusIcon(task);

              return (
                <div
                  key={`scheduled-${task.id}`}
                  className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6 hover:shadow-md transition-shadow"
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-2">
                        <span className="px-2 py-0.5 text-xs font-medium bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded">
                          Scheduled
                        </span>
                        <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                          {task.name}
                        </h3>
                        <StatusIcon className={`w-5 h-5 ${getStatusColor(task)}`} />
                      </div>

                      {task.description && (
                        <p className="text-gray-600 dark:text-gray-400 text-sm mb-3">
                          {task.description}
                        </p>
                      )}

                      <div className="flex flex-wrap items-center gap-4 text-sm">
                        <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
                          <Zap className="w-4 h-4" />
                          <span>{task.plugin_display_name}</span>
                        </div>

                        <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
                          <ScheduleIcon className="w-4 h-4" />
                          <span>{getScheduleDisplay(task)}</span>
                        </div>

                        {task.next_run_at && task.status === 'ACTIVE' && (
                          <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
                            <Clock className="w-4 h-4" />
                            <span>Next: {new Date(task.next_run_at).toLocaleString()}</span>
                          </div>
                        )}

                        {task.last_run_at && (
                          <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
                            <CheckCircle2 className="w-4 h-4" />
                            <span>Last: {new Date(task.last_run_at).toLocaleString()}</span>
                          </div>
                        )}
                      </div>
                    </div>

                    {/* Actions */}
                    <div className="flex items-center gap-2 ml-4">
                      <button
                        onClick={() => triggerMutation.mutate(task.id)}
                        className="p-2 text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg transition-colors"
                        title="Run now"
                      >
                        <Play className="w-5 h-5" />
                      </button>

                      <button
                        onClick={() => toggleActiveMutation.mutate({
                          taskId: task.id,
                          status: task.status === 'ACTIVE' ? 'PAUSED' : 'ACTIVE'
                        })}
                        className={`p-2 rounded-lg transition-colors ${
                          task.status === 'ACTIVE'
                            ? 'text-orange-600 dark:text-orange-400 hover:bg-orange-50 dark:hover:bg-orange-900/20'
                            : 'text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-900/20'
                        }`}
                        title={task.status === 'ACTIVE' ? 'Pause' : 'Resume'}
                      >
                        {task.status === 'ACTIVE' ? <Pause className="w-5 h-5" /> : <Play className="w-5 h-5" />}
                      </button>

                      <button
                        onClick={() => setEditingTask(task)}
                        className="p-2 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                        title="Edit"
                      >
                        <Edit className="w-5 h-5" />
                      </button>

                      <button
                        onClick={() => {
                          if (confirm('Are you sure you want to delete this task?')) {
                            deleteMutation.mutate(task.id);
                          }
                        }}
                        className="p-2 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
                        title="Delete"
                      >
                        <Trash2 className="w-5 h-5" />
                      </button>
                    </div>
                  </div>
                </div>
              );
            } else {
              // Event automation
              const automation = unifiedTask.data;

              return (
                <div
                  key={`event-${automation.id}`}
                  className={`bg-white dark:bg-gray-800 rounded-lg border p-6 hover:shadow-md transition-shadow ${
                    automation.is_active
                      ? 'border-gray-200 dark:border-gray-700'
                      : 'border-gray-200 dark:border-gray-700 opacity-60'
                  }`}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-2">
                        <span className="px-2 py-0.5 text-xs font-medium bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 rounded">
                          Event Automation
                        </span>
                        <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                          {automation.plugin_name}
                        </h3>
                        {automation.is_active ? (
                          <CheckCircle2 className="w-5 h-5 text-green-600 dark:text-green-400" />
                        ) : (
                          <Pause className="w-5 h-5 text-gray-400" />
                        )}
                      </div>

                      {automation.plugin_description && (
                        <p className="text-gray-600 dark:text-gray-400 text-sm mb-3">
                          {automation.plugin_description}
                        </p>
                      )}

                      <div className="flex flex-wrap items-center gap-4 text-sm">
                        <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
                          <CalendarDays className="w-4 h-4" />
                          <span>{automation.timing_description}</span>
                        </div>

                        <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
                          <Zap className="w-4 h-4" />
                          <span>{automation.events_count} events</span>
                        </div>

                        <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
                          <span className={`px-2 py-0.5 text-xs rounded ${
                            automation.apply_to_existing
                              ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300'
                              : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400'
                          }`}>
                            {automation.apply_to_existing ? 'All events' : 'Future only'}
                          </span>
                        </div>
                      </div>
                    </div>

                    {/* Actions */}
                    <div className="flex items-center gap-2 ml-4">
                      <button
                        onClick={() => toggleEventAutomationMutation.mutate(automation.id)}
                        className={`p-2 rounded-lg transition-colors ${
                          automation.is_active
                            ? 'text-orange-600 dark:text-orange-400 hover:bg-orange-50 dark:hover:bg-orange-900/20'
                            : 'text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-900/20'
                        }`}
                        title={automation.is_active ? 'Disable' : 'Enable'}
                      >
                        <Power className="w-5 h-5" />
                      </button>

                      <button
                        onClick={() => setEditingEventAutomation(automation)}
                        className="p-2 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                        title="Edit"
                      >
                        <Edit className="w-5 h-5" />
                      </button>

                      <button
                        onClick={() => {
                          if (confirm('Are you sure you want to delete this automation? It will be removed from all events.')) {
                            deleteEventAutomationMutation.mutate(automation.id);
                          }
                        }}
                        className="p-2 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
                        title="Delete"
                      >
                        <Trash2 className="w-5 h-5" />
                      </button>
                    </div>
                  </div>
                </div>
              );
            }
          })}
        </div>
      )}

      {/* Create Task Modal */}
      <CreateTaskModal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        onSuccess={() => {
          queryClient.invalidateQueries({ queryKey: ['scheduled-tasks'] });
          queryClient.invalidateQueries({ queryKey: ['global-event-plugins'] });
        }}
      />

      {/* Edit Task Modal */}
      <EditTaskModal
        task={editingTask}
        isOpen={!!editingTask}
        onClose={() => setEditingTask(null)}
        onSuccess={() => {
          queryClient.invalidateQueries({ queryKey: ['scheduled-tasks'] });
          toast.success('Task updated successfully');
        }}
      />

      {/* Edit Event Automation Modal */}
      {editingEventAutomation && (
        <EditEventAutomationModal
          automation={editingEventAutomation}
          isOpen={!!editingEventAutomation}
          onClose={() => setEditingEventAutomation(null)}
          onSave={(data) => updateEventAutomationMutation.mutate({ id: editingEventAutomation.id, data })}
          isLoading={updateEventAutomationMutation.isPending}
        />
      )}
    </div>
    </LockedSection>
  );
};

// Inline Edit Event Automation Modal component
interface EditEventAutomationModalProps {
  automation: GlobalEventPlugin;
  isOpen: boolean;
  onClose: () => void;
  onSave: (data: Partial<GlobalEventPlugin>) => void;
  isLoading: boolean;
}

const TRIGGER_OPTIONS = [
  { value: 'before_start', label: 'Before Start' },
  { value: 'at_start', label: 'At Start' },
  { value: 'after_start', label: 'After Start' },
  { value: 'after_end', label: 'After End' },
  { value: 'on_complete', label: 'When Completed' },
  { value: 'on_cancel', label: 'When Canceled' },
];

const OFFSET_PRESETS = [
  { value: 0, label: 'Immediately' },
  { value: 5, label: '5 min' },
  { value: 10, label: '10 min' },
  { value: 15, label: '15 min' },
  { value: 30, label: '30 min' },
  { value: 60, label: '1 hour' },
];

const EditEventAutomationModal: React.FC<EditEventAutomationModalProps> = ({
  automation,
  isOpen,
  onClose,
  onSave,
  isLoading,
}) => {
  const [trigger, setTrigger] = useState(automation.trigger);
  const [offsetMinutes, setOffsetMinutes] = useState(automation.offset_minutes);

  const showOffset = !['on_complete', 'on_cancel'].includes(trigger);

  const getTimingDescription = () => {
    if (trigger === 'on_complete') return 'When event is completed';
    if (trigger === 'on_cancel') return 'When event is canceled';

    if (offsetMinutes === 0) {
      if (trigger === 'before_start' || trigger === 'at_start' || trigger === 'after_start') return 'At event start';
      if (trigger === 'after_end') return 'At event end';
    }

    const offsetLabel = OFFSET_PRESETS.find(o => o.value === offsetMinutes)?.label || `${offsetMinutes} min`;
    if (trigger === 'before_start') return `${offsetLabel} before event starts`;
    if (trigger === 'at_start' || trigger === 'after_start') return `${offsetLabel} after event starts`;
    if (trigger === 'after_end') return `${offsetLabel} after event ends`;

    return 'Unknown timing';
  };

  const handleSave = () => {
    onSave({
      trigger,
      offset_minutes: offsetMinutes,
    });
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
      <div className="bg-white dark:bg-gray-800 rounded-lg max-w-lg w-full">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
          <h2 className="text-xl font-bold text-gray-900 dark:text-white">
            Edit Event Automation
          </h2>
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700"
          >
            <XCircle className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6 space-y-6">
          {/* Plugin info */}
          <div className="p-4 bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-800 rounded-lg">
            <div className="flex items-center gap-3">
              <Zap className="w-5 h-5 text-purple-600 dark:text-purple-400" />
              <div>
                <p className="text-sm text-purple-800 dark:text-purple-200 font-medium">
                  Plugin
                </p>
                <p className="text-purple-900 dark:text-purple-100">
                  {automation.plugin_name}
                </p>
              </div>
            </div>
          </div>

          {/* When to run */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
              When should it run?
            </label>
            <div className="grid grid-cols-2 gap-2">
              {TRIGGER_OPTIONS.map((opt) => (
                <button
                  key={opt.value}
                  type="button"
                  onClick={() => {
                    setTrigger(opt.value);
                    if (['on_complete', 'on_cancel'].includes(opt.value)) {
                      setOffsetMinutes(0);
                    }
                  }}
                  className={`px-3 py-2 text-sm rounded-lg border transition-colors ${
                    trigger === opt.value
                      ? 'bg-purple-600 text-white border-purple-600'
                      : 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:border-purple-400'
                  }`}
                >
                  {opt.label}
                </button>
              ))}
            </div>
          </div>

          {/* Offset selection */}
          {showOffset && (
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                How long {trigger === 'before_start' ? 'before' : 'after'}?
              </label>
              <div className="flex flex-wrap gap-2">
                {OFFSET_PRESETS.map((preset) => (
                  <button
                    key={preset.value}
                    type="button"
                    onClick={() => setOffsetMinutes(preset.value)}
                    className={`px-3 py-2 text-sm rounded-lg border transition-colors ${
                      offsetMinutes === preset.value
                        ? 'bg-purple-600 text-white border-purple-600'
                        : 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:border-purple-400'
                    }`}
                  >
                    {preset.label}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Preview */}
          <div className="p-3 bg-purple-100 dark:bg-purple-900/30 border border-purple-300 dark:border-purple-700 rounded-lg">
            <div className="flex items-center gap-2">
              <CalendarDays className="w-4 h-4 text-purple-600 dark:text-purple-400" />
              <span className="text-sm text-purple-800 dark:text-purple-200">
                <strong>Runs:</strong> {getTimingDescription()}
              </span>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700">
          <button
            onClick={onClose}
            className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={isLoading}
            className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50"
          >
            {isLoading ? 'Saving...' : 'Save Changes'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default Tasks;
