import React, { useState, useEffect } from 'react';
import axios from '../api/client';
import { X, Calendar, Clock, RotateCw, Zap } from 'lucide-react';
import { formatLocalDate } from '../utils/dateUtils';

interface ScheduledTask {
  id: string;
  name: string;
  description: string;
  automation_name: string;
  automation_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;
  automation_config: Record<string, any>;
  created_at: string;
  updated_at: string;
}

interface EditTaskModalProps {
  task: ScheduledTask | null;
  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[] = [
  { 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 },
  { 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 * *' },
];

const EditTaskModal: React.FC<EditTaskModalProps> = ({ task, isOpen, onClose, onSuccess }) => {
  const [taskName, setTaskName] = useState('');
  const [description, setDescription] = useState('');
  const [selectedPreset, setSelectedPreset] = useState<string>('');
  const [scheduleMode, setScheduleMode] = useState<'preset' | 'onetime' | 'advanced'>('preset');
  const [runAtDate, setRunAtDate] = useState('');
  const [runAtTime, setRunAtTime] = useState('');
  const [customCron, setCustomCron] = useState('0 0 * * *');

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

  // Load task data when modal opens
  useEffect(() => {
    if (task && isOpen) {
      setTaskName(task.name);
      setDescription(task.description || '');

      // Determine schedule mode and preset
      if (task.schedule_type === 'ONE_TIME') {
        setScheduleMode('onetime');
        if (task.run_at) {
          const date = new Date(task.run_at);
          setRunAtDate(formatLocalDate(date));
          setRunAtTime(date.toTimeString().slice(0, 5));
        }
      } else if (task.schedule_type === 'INTERVAL') {
        // Try to match to a preset
        const matchingPreset = SCHEDULE_PRESETS.find(
          p => p.type === 'INTERVAL' && p.interval_minutes === task.interval_minutes
        );
        if (matchingPreset) {
          setScheduleMode('preset');
          setSelectedPreset(matchingPreset.id);
        } else {
          setScheduleMode('advanced');
          // Convert interval to rough cron (not perfect, but gives user a starting point)
          setCustomCron(`*/${task.interval_minutes} * * * *`);
        }
      } else if (task.schedule_type === 'CRON' && task.cron_expression) {
        // Try to match to a preset
        const matchingPreset = SCHEDULE_PRESETS.find(
          p => p.type === 'CRON' && p.cron_expression === task.cron_expression
        );
        if (matchingPreset) {
          setScheduleMode('preset');
          setSelectedPreset(matchingPreset.id);
        } else {
          setScheduleMode('advanced');
          setCustomCron(task.cron_expression);
        }
      }
    }
  }, [task, isOpen]);

  const handleClose = () => {
    setError('');
    onClose();
  };

  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 handleSubmit = async () => {
    if (!task) return;

    setIsSubmitting(true);
    setError('');

    try {
      let payload: any = {
        name: taskName,
        description,
      };

      if (scheduleMode === 'onetime') {
        payload.schedule_type = 'ONE_TIME';
        payload.run_at = `${runAtDate}T${runAtTime}:00`;
        payload.interval_minutes = null;
        payload.cron_expression = null;
      } else if (scheduleMode === 'advanced') {
        payload.schedule_type = 'CRON';
        payload.cron_expression = customCron;
        payload.interval_minutes = null;
        payload.run_at = null;
      } 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;
            payload.cron_expression = null;
          } else {
            payload.cron_expression = preset.cron_expression;
            payload.interval_minutes = null;
          }
          payload.run_at = null;
        }
      }

      await axios.patch(`/scheduled-tasks/${task.id}/`, payload);
      onSuccess();
      handleClose();
    } catch (err: any) {
      setError(err.response?.data?.detail || 'Failed to update task');
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!isOpen || !task) 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">
            Edit 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>

        {/* Content */}
        <div className="p-6 space-y-6">
          {/* Automation Info (read-only) */}
          <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">
                  Automation
                </p>
                <p className="text-blue-900 dark:text-blue-100">
                  {task.automation_display_name}
                </p>
              </div>
            </div>
          </div>

          {/* 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"
            />
          </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>

          {/* 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>

        {/* 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={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>
          <button
            onClick={handleSubmit}
            disabled={isSubmitting || !taskName || (scheduleMode === 'onetime' && (!runAtDate || !runAtTime)) || (scheduleMode === 'preset' && !selectedPreset)}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isSubmitting ? 'Saving...' : 'Save Changes'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default EditTaskModal;
