import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from '../api/client';
import { X, Calendar, Clock, RotateCw, Zap, CalendarDays, ChevronDown, ChevronUp } from 'lucide-react';
import toast from 'react-hot-toast';

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 CreateTaskModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

// Schedule presets for visual selection
interface SchedulePreset {
  id: string;
  label: string;
  description: string;
  type: 'INTERVAL' | 'CRON';
  interval_minutes?: number;
  cron_expression?: string;
}

const SCHEDULE_PRESETS: SchedulePreset[] = [
  // Interval-based
  { id: 'every_15min', label: 'Every 15 minutes', description: 'Runs 4 times per hour', type: 'INTERVAL', interval_minutes: 15 },
  { id: 'every_30min', label: 'Every 30 minutes', description: 'Runs twice per hour', type: 'INTERVAL', interval_minutes: 30 },
  { id: 'every_hour', label: 'Every hour', description: 'Runs 24 times per day', type: 'INTERVAL', interval_minutes: 60 },
  { id: 'every_2hours', label: 'Every 2 hours', description: 'Runs 12 times per day', type: 'INTERVAL', interval_minutes: 120 },
  { id: 'every_4hours', label: 'Every 4 hours', description: 'Runs 6 times per day', type: 'INTERVAL', interval_minutes: 240 },
  { id: 'every_6hours', label: 'Every 6 hours', description: 'Runs 4 times per day', type: 'INTERVAL', interval_minutes: 360 },
  { id: 'every_12hours', label: 'Twice daily', description: 'Runs at midnight and noon', type: 'INTERVAL', interval_minutes: 720 },
  // Cron-based (specific times)
  { id: 'daily_midnight', label: 'Daily at midnight', description: 'Runs once per day at 12:00 AM', type: 'CRON', cron_expression: '0 0 * * *' },
  { id: 'daily_9am', label: 'Daily at 9 AM', description: 'Runs once per day at 9:00 AM', type: 'CRON', cron_expression: '0 9 * * *' },
  { id: 'daily_6pm', label: 'Daily at 6 PM', description: 'Runs once per day at 6:00 PM', type: 'CRON', cron_expression: '0 18 * * *' },
  { id: 'weekdays_9am', label: 'Weekdays at 9 AM', description: 'Mon-Fri at 9:00 AM', type: 'CRON', cron_expression: '0 9 * * 1-5' },
  { id: 'weekdays_6pm', label: 'Weekdays at 6 PM', description: 'Mon-Fri at 6:00 PM', type: 'CRON', cron_expression: '0 18 * * 1-5' },
  { id: 'weekly_sunday', label: 'Weekly on Sunday', description: 'Every Sunday at midnight', type: 'CRON', cron_expression: '0 0 * * 0' },
  { id: 'weekly_monday', label: 'Weekly on Monday', description: 'Every Monday at 9:00 AM', type: 'CRON', cron_expression: '0 9 * * 1' },
  { id: 'monthly_1st', label: 'Monthly on the 1st', description: 'First day of each month', type: 'CRON', cron_expression: '0 0 1 * *' },
];

// Event trigger options (same as EventAutomations component)
interface TriggerOption {
  value: string;
  label: string;
}

interface OffsetPreset {
  value: number;
  label: string;
}

const TRIGGER_OPTIONS: TriggerOption[] = [
  { 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: OffsetPreset[] = [
  { 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' },
];

// Task type: scheduled or event-based
type TaskType = 'scheduled' | 'event';

const CreateTaskModal: React.FC<CreateTaskModalProps> = ({ isOpen, onClose, onSuccess }) => {
  const queryClient = useQueryClient();
  const [step, setStep] = useState(1);
  const [selectedPlugin, setSelectedPlugin] = useState<PluginInstallation | null>(null);
  const [taskName, setTaskName] = useState('');
  const [description, setDescription] = useState('');

  // Task type selection
  const [taskType, setTaskType] = useState<TaskType>('scheduled');

  // Schedule selection (for scheduled tasks)
  const [selectedPreset, setSelectedPreset] = useState<string>('every_hour');
  const [scheduleMode, setScheduleMode] = useState<'preset' | 'onetime' | 'advanced'>('preset');

  // One-time schedule
  const [runAtDate, setRunAtDate] = useState('');
  const [runAtTime, setRunAtTime] = useState('');

  // Advanced (custom cron)
  const [customCron, setCustomCron] = useState('0 0 * * *');

  // Event automation settings (for event tasks)
  const [selectedTrigger, setSelectedTrigger] = useState<string>('at_start');
  const [selectedOffset, setSelectedOffset] = useState<number>(0);
  const [applyToExisting, setApplyToExisting] = useState<boolean>(true);

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState('');

  // Fetch available plugins
  const { data: plugins = [], isLoading: pluginsLoading } = useQuery<PluginInstallation[]>({
    queryKey: ['plugin-installations'],
    queryFn: async () => {
      const { data } = await axios.get('/plugin-installations/');
      // Filter out plugins that already have scheduled tasks
      return data.filter((p: PluginInstallation) => !p.scheduled_task);
    },
    enabled: isOpen,
  });

  const handleClose = () => {
    setStep(1);
    setSelectedPlugin(null);
    setTaskName('');
    setDescription('');
    setError('');
    setTaskType('scheduled');
    setScheduleMode('preset');
    setSelectedPreset('every_hour');
    setSelectedTrigger('at_start');
    setSelectedOffset(0);
    setApplyToExisting(true);
    setRunAtDate('');
    setRunAtTime('');
    setCustomCron('0 0 * * *');
    onClose();
  };

  const handlePluginSelect = (plugin: PluginInstallation) => {
    setSelectedPlugin(plugin);
    setTaskName(`${plugin.template_name} - Scheduled Task`);
    setStep(2);
  };

  const getScheduleDescription = () => {
    if (scheduleMode === 'onetime') {
      if (runAtDate && runAtTime) {
        return `Once on ${new Date(`${runAtDate}T${runAtTime}`).toLocaleString()}`;
      }
      return 'Select date and time';
    }
    if (scheduleMode === 'advanced') {
      return `Custom: ${customCron}`;
    }
    const preset = SCHEDULE_PRESETS.find(p => p.id === selectedPreset);
    return preset?.description || 'Select a schedule';
  };

  const getEventTimingDescription = () => {
    const trigger = TRIGGER_OPTIONS.find(t => t.value === selectedTrigger);
    if (!trigger) return 'Select timing';

    if (selectedTrigger === 'on_complete') return 'When event is completed';
    if (selectedTrigger === 'on_cancel') return 'When event is canceled';

    if (selectedOffset === 0) {
      if (selectedTrigger === 'before_start') return 'At event start';
      if (selectedTrigger === 'at_start') return 'At event start';
      if (selectedTrigger === 'after_start') return 'At event start';
      if (selectedTrigger === 'after_end') return 'At event end';
    }

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

    return trigger.label;
  };

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

  const handleSubmit = async () => {
    if (!selectedPlugin) return;

    setIsSubmitting(true);
    setError('');

    try {
      if (taskType === 'event') {
        // Create global event plugin (applies to all events)
        const payload = {
          plugin_installation: selectedPlugin.id,
          trigger: selectedTrigger,
          offset_minutes: selectedOffset,
          is_active: true,
          apply_to_existing: applyToExisting,
        };

        await axios.post('/global-event-plugins/', payload);
        queryClient.invalidateQueries({ queryKey: ['global-event-plugins'] });
        toast.success(applyToExisting ? 'Plugin attached to all events' : 'Plugin will apply to future events');
      } else {
        // Create scheduled task
        let payload: any = {
          name: taskName,
          description,
          plugin_name: selectedPlugin.template_slug,
          status: 'ACTIVE',
          plugin_config: selectedPlugin.config_values || {},
        };

        if (scheduleMode === 'onetime') {
          payload.schedule_type = 'ONE_TIME';
          payload.run_at = `${runAtDate}T${runAtTime}:00`;
        } else if (scheduleMode === 'advanced') {
          payload.schedule_type = 'CRON';
          payload.cron_expression = customCron;
        } else {
          const preset = SCHEDULE_PRESETS.find(p => p.id === selectedPreset);
          if (preset) {
            payload.schedule_type = preset.type;
            if (preset.type === 'INTERVAL') {
              payload.interval_minutes = preset.interval_minutes;
            } else {
              payload.cron_expression = preset.cron_expression;
            }
          }
        }

        await axios.post('/scheduled-tasks/', payload);
        toast.success('Scheduled task created');
      }

      onSuccess();
      handleClose();
    } catch (err: any) {
      setError(err.response?.data?.detail || err.response?.data?.error || 'Failed to create task');
    } finally {
      setIsSubmitting(false);
    }
  };

  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-2xl w-full max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white">
            Schedule a Task
          </h2>
          <button
            onClick={handleClose}
            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"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Steps indicator */}
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-center gap-4">
            <div className={`flex items-center gap-2 ${step >= 1 ? 'text-blue-600 dark:text-blue-400' : 'text-gray-400'}`}>
              <div className={`w-8 h-8 rounded-full flex items-center justify-center ${step >= 1 ? 'bg-blue-600 text-white' : 'bg-gray-200 dark:bg-gray-700 text-gray-500'}`}>
                1
              </div>
              <span className="font-medium">Select Plugin</span>
            </div>
            <div className="w-16 h-0.5 bg-gray-200 dark:bg-gray-700" />
            <div className={`flex items-center gap-2 ${step >= 2 ? 'text-blue-600 dark:text-blue-400' : 'text-gray-400'}`}>
              <div className={`w-8 h-8 rounded-full flex items-center justify-center ${step >= 2 ? 'bg-blue-600 text-white' : 'bg-gray-200 dark:bg-gray-700 text-gray-500'}`}>
                2
              </div>
              <span className="font-medium">Configure</span>
            </div>
          </div>
        </div>

        {/* Content */}
        <div className="p-6">
          {/* Step 1: Select Plugin */}
          {step === 1 && (
            <div>
              <p className="text-gray-600 dark:text-gray-400 mb-4">
                Select a plugin to schedule for automatic execution.
              </p>

              {pluginsLoading ? (
                <div className="flex items-center justify-center py-12">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                </div>
              ) : plugins.length === 0 ? (
                <div className="text-center py-12 bg-gray-50 dark:bg-gray-900 rounded-lg">
                  <Zap className="w-12 h-12 text-gray-400 mx-auto mb-3" />
                  <p className="text-gray-600 dark:text-gray-400 mb-2">No available plugins</p>
                  <p className="text-sm text-gray-500 dark:text-gray-500">
                    Install plugins from the Marketplace first, or all your plugins are already scheduled.
                  </p>
                </div>
              ) : (
                <div className="grid grid-cols-1 gap-3 max-h-96 overflow-y-auto">
                  {plugins.map((plugin) => (
                    <button
                      key={plugin.id}
                      onClick={() => handlePluginSelect(plugin)}
                      className="text-left p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:border-blue-500 dark:hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-colors"
                    >
                      <div className="flex items-start gap-3">
                        {plugin.logo_url ? (
                          <img src={plugin.logo_url} alt="" className="w-10 h-10 rounded" />
                        ) : (
                          <div className="w-10 h-10 rounded bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
                            <Zap className="w-5 h-5 text-blue-600 dark:text-blue-400" />
                          </div>
                        )}
                        <div className="flex-1">
                          <h3 className="font-semibold text-gray-900 dark:text-white mb-1">
                            {plugin.template_name}
                          </h3>
                          <p className="text-sm text-gray-600 dark:text-gray-400 line-clamp-2">
                            {plugin.template_description}
                          </p>
                        </div>
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Step 2: Configure Schedule */}
          {step === 2 && selectedPlugin && (
            <div className="space-y-6">
              {/* Selected Plugin */}
              <div className="p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
                <div className="flex items-center gap-3">
                  <Zap className="w-5 h-5 text-blue-600 dark:text-blue-400" />
                  <div>
                    <p className="text-sm text-blue-800 dark:text-blue-200 font-medium">
                      Selected Plugin
                    </p>
                    <p className="text-blue-900 dark:text-blue-100">
                      {selectedPlugin.template_name}
                    </p>
                  </div>
                </div>
              </div>

              {/* Task Type Selection */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                  How should this plugin run?
                </label>
                <div className="grid grid-cols-2 gap-3">
                  <button
                    onClick={() => setTaskType('scheduled')}
                    className={`p-4 rounded-lg border-2 text-left transition-all ${
                      taskType === 'scheduled'
                        ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                        : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
                    }`}
                  >
                    <div className="flex items-center gap-2 mb-2">
                      <Clock className={`w-5 h-5 ${taskType === 'scheduled' ? 'text-blue-600 dark:text-blue-400' : 'text-gray-400'}`} />
                      <span className={`font-semibold ${taskType === 'scheduled' ? 'text-blue-700 dark:text-blue-300' : 'text-gray-900 dark:text-white'}`}>
                        Scheduled Task
                      </span>
                    </div>
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      Run on a fixed schedule (hourly, daily, weekly, etc.)
                    </p>
                  </button>
                  <button
                    onClick={() => setTaskType('event')}
                    className={`p-4 rounded-lg border-2 text-left transition-all ${
                      taskType === 'event'
                        ? 'border-purple-500 bg-purple-50 dark:bg-purple-900/20'
                        : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
                    }`}
                  >
                    <div className="flex items-center gap-2 mb-2">
                      <CalendarDays className={`w-5 h-5 ${taskType === 'event' ? 'text-purple-600 dark:text-purple-400' : 'text-gray-400'}`} />
                      <span className={`font-semibold ${taskType === 'event' ? 'text-purple-700 dark:text-purple-300' : 'text-gray-900 dark:text-white'}`}>
                        Event Automation
                      </span>
                    </div>
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      Run for every appointment on your calendar
                    </p>
                  </button>
                </div>
              </div>

              {/* Scheduled Task Options */}
              {taskType === 'scheduled' && (
                <>
                  {/* Task Name */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Task Name
                    </label>
                    <input
                      type="text"
                      value={taskName}
                      onChange={(e) => setTaskName(e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white"
                      placeholder="e.g., Daily Customer Report"
                    />
                  </div>

                  {/* Schedule Mode Tabs */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                      Schedule
                    </label>
                    <div className="flex border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden mb-4">
                      <button
                        onClick={() => setScheduleMode('preset')}
                        className={`flex-1 px-4 py-2 text-sm font-medium transition-colors ${
                          scheduleMode === 'preset'
                            ? 'bg-blue-600 text-white'
                            : 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                        }`}
                      >
                        <RotateCw className="w-4 h-4 inline mr-2" />
                        Recurring
                      </button>
                      <button
                        onClick={() => setScheduleMode('onetime')}
                        className={`flex-1 px-4 py-2 text-sm font-medium transition-colors ${
                          scheduleMode === 'onetime'
                            ? 'bg-blue-600 text-white'
                            : 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                        }`}
                      >
                        <Calendar className="w-4 h-4 inline mr-2" />
                        One-Time
                      </button>
                      <button
                        onClick={() => setScheduleMode('advanced')}
                        className={`flex-1 px-4 py-2 text-sm font-medium transition-colors ${
                          scheduleMode === 'advanced'
                            ? 'bg-blue-600 text-white'
                            : 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                        }`}
                      >
                        <Clock className="w-4 h-4 inline mr-2" />
                        Advanced
                      </button>
                    </div>

                    {/* Preset Selection */}
                    {scheduleMode === 'preset' && (
                      <div className="grid grid-cols-2 gap-2 max-h-64 overflow-y-auto">
                        {SCHEDULE_PRESETS.map((preset) => (
                          <button
                            key={preset.id}
                            onClick={() => setSelectedPreset(preset.id)}
                            className={`text-left p-3 rounded-lg border transition-colors ${
                              selectedPreset === preset.id
                                ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                                : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
                            }`}
                          >
                            <p className={`text-sm font-medium ${selectedPreset === preset.id ? 'text-blue-700 dark:text-blue-300' : 'text-gray-900 dark:text-white'}`}>
                              {preset.label}
                            </p>
                            <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                              {preset.description}
                            </p>
                          </button>
                        ))}
                      </div>
                    )}

                    {/* One-Time Selection */}
                    {scheduleMode === 'onetime' && (
                      <div className="grid grid-cols-2 gap-4 p-4 bg-gray-50 dark:bg-gray-900 rounded-lg">
                        <div>
                          <label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">
                            Date
                          </label>
                          <input
                            type="date"
                            value={runAtDate}
                            onChange={(e) => setRunAtDate(e.target.value)}
                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                          />
                        </div>
                        <div>
                          <label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">
                            Time
                          </label>
                          <input
                            type="time"
                            value={runAtTime}
                            onChange={(e) => setRunAtTime(e.target.value)}
                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                          />
                        </div>
                      </div>
                    )}

                    {/* Advanced Cron */}
                    {scheduleMode === 'advanced' && (
                      <div className="p-4 bg-gray-50 dark:bg-gray-900 rounded-lg space-y-3">
                        <div>
                          <label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">
                            Cron Expression
                          </label>
                          <input
                            type="text"
                            value={customCron}
                            onChange={(e) => setCustomCron(e.target.value)}
                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white font-mono text-sm"
                        placeholder="0 0 * * *"
                      />
                      <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                        Format: minute hour day month weekday (e.g., "0 9 * * 1-5" = weekdays at 9 AM)
                      </p>
                    </div>
                  </div>
                )}
                  </div>

                  {/* Schedule Preview */}
                  <div className="p-3 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
                    <div className="flex items-center gap-2">
                      <Clock className="w-4 h-4 text-green-600 dark:text-green-400" />
                      <span className="text-sm text-green-800 dark:text-green-200">
                        <strong>Schedule:</strong> {getScheduleDescription()}
                      </span>
                    </div>
                  </div>
                </>
              )}

              {/* Event Automation Options */}
              {taskType === 'event' && (
                <>
                  {/* Apply to which events */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                      Apply to which events?
                    </label>
                    <div className="grid grid-cols-2 gap-3">
                      <button
                        onClick={() => setApplyToExisting(true)}
                        className={`p-3 rounded-lg border-2 text-left transition-all ${
                          applyToExisting
                            ? 'border-purple-500 bg-purple-50 dark:bg-purple-900/20'
                            : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
                        }`}
                      >
                        <span className={`font-medium text-sm ${applyToExisting ? 'text-purple-700 dark:text-purple-300' : 'text-gray-900 dark:text-white'}`}>
                          All Events
                        </span>
                        <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                          Existing + future appointments
                        </p>
                      </button>
                      <button
                        onClick={() => setApplyToExisting(false)}
                        className={`p-3 rounded-lg border-2 text-left transition-all ${
                          !applyToExisting
                            ? 'border-purple-500 bg-purple-50 dark:bg-purple-900/20'
                            : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
                        }`}
                      >
                        <span className={`font-medium text-sm ${!applyToExisting ? 'text-purple-700 dark:text-purple-300' : 'text-gray-900 dark:text-white'}`}>
                          Future Only
                        </span>
                        <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                          Only new appointments
                        </p>
                      </button>
                    </div>
                  </div>

                  {/* Info about timing updates */}
                  <div className="p-3 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg">
                    <p className="text-xs text-gray-600 dark:text-gray-400">
                      If an event is rescheduled, the plugin timing will automatically update.
                    </p>
                  </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={() => {
                            setSelectedTrigger(opt.value);
                            if (['on_complete', 'on_cancel'].includes(opt.value)) {
                              setSelectedOffset(0);
                            }
                          }}
                          className={`px-3 py-2 text-sm rounded-lg border transition-colors ${
                            selectedTrigger === 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 (only for time-based triggers) */}
                  {showOffset && (
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                        How long {selectedTrigger === 'before_start' ? 'before' : 'after'}?
                      </label>
                      <div className="flex flex-wrap gap-2">
                        {OFFSET_PRESETS.map((preset) => (
                          <button
                            key={preset.value}
                            type="button"
                            onClick={() => setSelectedOffset(preset.value)}
                            className={`px-3 py-2 text-sm rounded-lg border transition-colors ${
                              selectedOffset === 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>
                  )}

                  {/* Event Timing 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> {getEventTimingDescription()}
                      </span>
                    </div>
                  </div>
                </>
              )}

              {/* Error */}
              {error && (
                <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
                  <p className="text-sm text-red-800 dark:text-red-200">{error}</p>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700">
          {step === 2 && (
            <button
              onClick={() => setStep(1)}
              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"
            >
              Back
            </button>
          )}
          <div className="flex-1" />
          <button
            onClick={handleClose}
            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>
          {step === 2 && (
            <button
              onClick={handleSubmit}
              disabled={
                isSubmitting ||
                (taskType === 'scheduled' && !taskName) ||
                (taskType === 'scheduled' && scheduleMode === 'onetime' && (!runAtDate || !runAtTime))
              }
              className={`px-4 py-2 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${
                taskType === 'event' ? 'bg-purple-600 hover:bg-purple-700' : 'bg-blue-600 hover:bg-blue-700'
              }`}
            >
              {isSubmitting
                ? 'Creating...'
                : taskType === 'event'
                ? 'Attach to All Events'
                : 'Create Task'}
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

export default CreateTaskModal;
