import React, { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import axios from '../api/client';
import { X, Calendar, Clock, RotateCw, Zap, CalendarDays } from 'lucide-react';
import toast from 'react-hot-toast';
import {
  SCHEDULE_PRESETS,
  TRIGGER_OPTIONS,
  OFFSET_PRESETS,
  getScheduleDescription,
  getEventTimingDescription,
} from '../constants/schedulePresets';
import { ErrorMessage } from './ui';

interface AutomationInstallation {
  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, unknown>;
  scheduled_task?: number;
  scheduled_task_name?: string;
  installed_at: string;
  config_values: Record<string, unknown>;
  has_update: boolean;
}

interface CreateTaskModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

// 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 [selectedAutomation, setSelectedAutomation] = useState<AutomationInstallation | 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 automations
  const { data: automations = [], isLoading: automationsLoading } = useQuery<AutomationInstallation[]>({
    queryKey: ['automation-installations'],
    queryFn: async () => {
      const { data } = await axios.get('/automation-installations/');
      // Filter out automations that already have scheduled tasks
      return data.filter((p: AutomationInstallation) => !p.scheduled_task);
    },
    enabled: isOpen,
  });

  const handleClose = () => {
    setStep(1);
    setSelectedAutomation(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 handleAutomationSelect = (automation: AutomationInstallation) => {
    setSelectedAutomation(automation);
    setTaskName(`${automation.template_name} - Scheduled Task`);
    setStep(2);
  };

  // Use shared helper functions from constants
  const scheduleDescriptionText = getScheduleDescription(
    scheduleMode,
    selectedPreset,
    runAtDate,
    runAtTime,
    customCron
  );

  const eventTimingDescriptionText = getEventTimingDescription(selectedTrigger, selectedOffset);

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

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

    setIsSubmitting(true);
    setError('');

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

        await axios.post('/global-event-automations/', payload);
        queryClient.invalidateQueries({ queryKey: ['global-event-automations'] });
        toast.success(applyToExisting ? 'Automation attached to all events' : 'Automation will apply to future events');
      } else {
        // Create scheduled task
        let payload: any = {
          name: taskName,
          description,
          automation_name: selectedAutomation.template_slug,
          status: 'ACTIVE',
          automation_config: selectedAutomation.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 Automation</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 Automation */}
          {step === 1 && (
            <div>
              <p className="text-gray-600 dark:text-gray-400 mb-4">
                Select an automation to schedule for automatic execution.
              </p>

              {automationsLoading ? (
                <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>
              ) : automations.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 automations</p>
                  <p className="text-sm text-gray-500 dark:text-gray-500">
                    Install automations from the Marketplace first, or all your automations are already scheduled.
                  </p>
                </div>
              ) : (
                <div className="grid grid-cols-1 gap-3 max-h-96 overflow-y-auto">
                  {automations.map((automation) => (
                    <button
                      key={automation.id}
                      onClick={() => handleAutomationSelect(automation)}
                      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">
                        {automation.logo_url ? (
                          <img src={automation.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">
                            {automation.template_name}
                          </h3>
                          <p className="text-sm text-gray-600 dark:text-gray-400 line-clamp-2">
                            {automation.template_description}
                          </p>
                        </div>
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Step 2: Configure Schedule */}
          {step === 2 && selectedAutomation && (
            <div className="space-y-6">
              {/* Selected Automation */}
              <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 Automation
                    </p>
                    <p className="text-blue-900 dark:text-blue-100">
                      {selectedAutomation.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 automation 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> {scheduleDescriptionText}
                      </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 automation 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> {eventTimingDescriptionText}
                      </span>
                    </div>
                  </div>
                </>
              )}

              {/* Error */}
              {error && <ErrorMessage message={error} />}
            </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;
