import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from '../api/client';
import { Zap, Plus, Trash2, Clock, CheckCircle2, XCircle, ChevronDown, Power } from 'lucide-react';
import toast from 'react-hot-toast';

interface AutomationInstallation {
  id: string;
  template_name: string;
  template_description: string;
  category: string;
  logo_url?: string;
}

interface EventAutomation {
  id: string;
  event: number;
  automation_installation: number;
  automation_name: string;
  automation_description: string;
  automation_category: string;
  automation_logo_url?: string;
  trigger: string;
  trigger_display: string;
  offset_minutes: number;
  timing_description: string;
  is_active: boolean;
  execution_order: number;
}

interface TriggerOption {
  value: string;
  label: string;
}

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

interface EventAutomationsProps {
  eventId: string | number;
  compact?: boolean;
}

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' },
];

const EventAutomations: React.FC<EventAutomationsProps> = ({ eventId, compact = false }) => {
  const queryClient = useQueryClient();
  const [showAddForm, setShowAddForm] = useState(false);
  const [selectedAutomation, setSelectedAutomation] = useState<string>('');
  const [selectedTrigger, setSelectedTrigger] = useState<string>('at_start');
  const [selectedOffset, setSelectedOffset] = useState<number>(0);

  // Fetch installed automations
  const { data: automations = [] } = useQuery<AutomationInstallation[]>({
    queryKey: ['automation-installations'],
    queryFn: async () => {
      const { data } = await axios.get('/automation-installations/');
      return data;
    },
  });

  // Fetch event automations
  const { data: eventAutomations = [], isLoading } = useQuery<EventAutomation[]>({
    queryKey: ['event-automations', eventId],
    queryFn: async () => {
      const { data } = await axios.get(`/event-automations/?event_id=${eventId}`);
      return data;
    },
    enabled: !!eventId,
  });

  // Add automation mutation
  const addMutation = useMutation({
    mutationFn: async (data: { automation_installation: string; trigger: string; offset_minutes: number }) => {
      return axios.post('/event-automations/', {
        event: eventId,
        ...data,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['event-automations', eventId] });
      setShowAddForm(false);
      setSelectedAutomation('');
      setSelectedTrigger('at_start');
      setSelectedOffset(0);
      toast.success('Automation added');
    },
    onError: () => {
      toast.error('Failed to add automation');
    },
  });

  // Toggle mutation
  const toggleMutation = useMutation({
    mutationFn: async (automationId: string) => {
      return axios.post(`/event-automations/${automationId}/toggle/`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['event-automations', eventId] });
    },
  });

  // Delete mutation
  const deleteMutation = useMutation({
    mutationFn: async (automationId: string) => {
      return axios.delete(`/event-automations/${automationId}/`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['event-automations', eventId] });
      toast.success('Automation removed');
    },
  });

  const handleAdd = () => {
    if (!selectedAutomation) return;
    addMutation.mutate({
      automation_installation: selectedAutomation,
      trigger: selectedTrigger,
      offset_minutes: selectedOffset,
    });
  };

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

  if (isLoading) {
    return (
      <div className="p-4 text-center text-gray-500 dark:text-gray-400">
        Loading automations...
      </div>
    );
  }

  return (
    <div className={`${compact ? 'space-y-3' : 'space-y-4'}`}>
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Zap className="w-4 h-4 text-purple-600 dark:text-purple-400" />
          <span className="text-sm font-medium text-gray-900 dark:text-white">
            Automations
          </span>
          {eventAutomations.length > 0 && (
            <span className="px-1.5 py-0.5 text-xs bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 rounded">
              {eventAutomations.length}
            </span>
          )}
        </div>
        {!showAddForm && automations.length > 0 && (
          <button
            onClick={() => setShowAddForm(true)}
            className="flex items-center gap-1 px-2 py-1 text-xs text-purple-600 dark:text-purple-400 hover:bg-purple-50 dark:hover:bg-purple-900/20 rounded transition-colors"
          >
            <Plus className="w-3 h-3" />
            Add
          </button>
        )}
      </div>

      {/* Existing automations */}
      {eventAutomations.length > 0 && (
        <div className="space-y-2">
          {eventAutomations.map((ep) => (
            <div
              key={ep.id}
              className={`flex items-center justify-between p-2 rounded-lg border ${
                ep.is_active
                  ? 'bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700'
                  : 'bg-gray-50 dark:bg-gray-900 border-gray-200 dark:border-gray-700 opacity-60'
              }`}
            >
              <div className="flex items-center gap-2 min-w-0">
                <div className={`p-1.5 rounded ${ep.is_active ? 'bg-purple-100 dark:bg-purple-900/30' : 'bg-gray-100 dark:bg-gray-800'}`}>
                  <Zap className={`w-3 h-3 ${ep.is_active ? 'text-purple-600 dark:text-purple-400' : 'text-gray-400'}`} />
                </div>
                <div className="min-w-0">
                  <p className="text-sm font-medium text-gray-900 dark:text-white truncate">
                    {ep.automation_name}
                  </p>
                  <div className="flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400">
                    <Clock className="w-3 h-3" />
                    <span>{ep.timing_description}</span>
                  </div>
                </div>
              </div>

              <div className="flex items-center gap-1">
                <button
                  onClick={() => toggleMutation.mutate(ep.id)}
                  className={`p-1.5 rounded transition-colors ${
                    ep.is_active
                      ? 'text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-900/20'
                      : 'text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700'
                  }`}
                  title={ep.is_active ? 'Disable' : 'Enable'}
                >
                  <Power className="w-3.5 h-3.5" />
                </button>
                <button
                  onClick={() => deleteMutation.mutate(ep.id)}
                  className="p-1.5 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors"
                  title="Remove"
                >
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Add automation form */}
      {showAddForm && (
        <div className="p-3 bg-purple-50 dark:bg-purple-900/20 rounded-lg border border-purple-200 dark:border-purple-800 space-y-3">
          {/* Automation selector */}
          <div>
            <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
              Automation
            </label>
            <select
              value={selectedAutomation}
              onChange={(e) => setSelectedAutomation(e.target.value)}
              className="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
            >
              <option value="">Select an automation...</option>
              {automations.map((a) => (
                <option key={a.id} value={a.id}>
                  {a.template_name}
                </option>
              ))}
            </select>
          </div>

          {/* Timing selector - visual */}
          <div>
            <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
              When to run
            </label>
            <div className="grid grid-cols-2 gap-1.5">
              {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-2 py-1.5 text-xs rounded 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 selector - only for time-based triggers */}
          {showOffset && (
            <div>
              <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                Offset
              </label>
              <div className="flex flex-wrap gap-1.5">
                {OFFSET_PRESETS.map((preset) => (
                  <button
                    key={preset.value}
                    type="button"
                    onClick={() => setSelectedOffset(preset.value)}
                    className={`px-2 py-1 text-xs rounded 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>
          )}

          {/* Preview */}
          {selectedAutomation && (
            <div className="text-xs text-purple-800 dark:text-purple-200 bg-purple-100 dark:bg-purple-900/40 px-2 py-1.5 rounded">
              Will run: <strong>
                {selectedTrigger === 'on_complete' ? 'When completed' :
                 selectedTrigger === 'on_cancel' ? 'When canceled' :
                 selectedTrigger === 'before_start' && selectedOffset > 0 ? `${selectedOffset} min before start` :
                 selectedTrigger === 'after_end' && selectedOffset > 0 ? `${selectedOffset} min after end` :
                 selectedTrigger === 'after_start' && selectedOffset > 0 ? `${selectedOffset} min after start` :
                 selectedTrigger === 'at_start' && selectedOffset > 0 ? `${selectedOffset} min after start` :
                 selectedTrigger === 'before_start' ? 'At start' :
                 selectedTrigger === 'after_end' ? 'At end' :
                 'At start'}
              </strong>
            </div>
          )}

          {/* Actions */}
          <div className="flex justify-end gap-2 pt-1">
            <button
              onClick={() => setShowAddForm(false)}
              className="px-3 py-1.5 text-xs text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
            >
              Cancel
            </button>
            <button
              onClick={handleAdd}
              disabled={!selectedAutomation || addMutation.isPending}
              className="px-3 py-1.5 text-xs bg-purple-600 text-white rounded hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {addMutation.isPending ? 'Adding...' : 'Add Automation'}
            </button>
          </div>
        </div>
      )}

      {/* Empty state */}
      {eventAutomations.length === 0 && !showAddForm && (
        <div className="text-center py-3 text-gray-500 dark:text-gray-400">
          {automations.length > 0 ? (
            <button
              onClick={() => setShowAddForm(true)}
              className="text-xs text-purple-600 dark:text-purple-400 hover:underline"
            >
              + Add your first automation
            </button>
          ) : (
            <p className="text-xs">
              Install automations from the Marketplace to use them
            </p>
          )}
        </div>
      )}
    </div>
  );
};

export default EventAutomations;
