import React, { useState } from 'react';
import { X, Plus, Trash2, GripVertical, Save } from 'lucide-react';
import { toast } from 'react-toastify';
import workflowService, { Workflow, WorkflowStep } from '../services/workflowService';

interface WorkflowBuilderProps {
  workflow?: Workflow | null;
  onClose: () => void;
  onSuccess: () => void;
}

const WorkflowBuilder: React.FC<WorkflowBuilderProps> = ({ workflow, onClose, onSuccess }) => {
  const [formData, setFormData] = useState({
    name: workflow?.name || '',
    description: workflow?.description || '',
    workflow_type: workflow?.workflow_type || 'custom',
    trigger: workflow?.trigger || 'manual',
    sla_hours: workflow?.sla_hours?.toString() || '',
    trigger_config: workflow?.trigger_config || {},
  });
  const [steps, setSteps] = useState<WorkflowStep[]>(workflow?.steps || []);
  const [loading, setLoading] = useState(false);

  const addStep = () => {
    setSteps([
      ...steps,
      {
        title: '',
        description: '',
        task_type: 'general',
        priority: 'medium',
        estimated_duration_minutes: 30,
      },
    ]);
  };

  const updateStep = (index: number, field: keyof WorkflowStep, value: string | number) => {
    const newSteps = [...steps];
    newSteps[index] = { ...newSteps[index], [field]: value };
    setSteps(newSteps);
  };

  const removeStep = (index: number) => {
    setSteps(steps.filter((_, i) => i !== index));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData.name.trim()) {
      toast.error('Workflow name is required');
      return;
    }

    if (steps.length === 0) {
      toast.error('At least one step is required');
      return;
    }

    if (steps.some(step => !step.title.trim())) {
      toast.error('All steps must have a title');
      return;
    }

    try {
      setLoading(true);
      if (workflow) {
        await workflowService.updateWorkflow(workflow.id, {
          name: formData.name,
          description: formData.description || undefined,
          steps: steps,
          trigger_config: formData.trigger_config,
          sla_hours: formData.sla_hours ? parseInt(formData.sla_hours) : undefined,
        });
        toast.success('Workflow updated successfully');
      } else {
        await workflowService.createWorkflow({
          name: formData.name,
          description: formData.description || undefined,
          workflow_type: formData.workflow_type as 'pre_arrival' | 'room_preparation' | 'maintenance' | 'guest_communication' | 'follow_up' | 'custom',
          trigger: formData.trigger as 'manual' | 'scheduled' | 'check_in' | 'check_out' | 'booking_created' | 'booking_confirmed' | 'maintenance_request' | 'guest_message',
          steps: steps,
          trigger_config: formData.trigger_config,
          sla_hours: formData.sla_hours ? parseInt(formData.sla_hours) : undefined,
        });
        toast.success('Workflow created successfully');
      }
      onSuccess();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to save workflow');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
        <div className="sticky top-0 bg-white border-b border-gray-200 p-6 flex items-center justify-between">
          <h2 className="text-2xl font-bold text-gray-900">
            {workflow ? 'Edit Workflow' : 'Create Workflow'}
          </h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          {/* Basic Information */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-gray-900">Basic Information</h3>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                Name <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">Description</label>
              <textarea
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                rows={3}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">Type</label>
                <select
                  value={formData.workflow_type}
                  onChange={(e) => setFormData({ ...formData, workflow_type: e.target.value as 'pre_arrival' | 'room_preparation' | 'maintenance' | 'guest_communication' | 'follow_up' | 'custom' })}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                  disabled={!!workflow}
                >
                  <option value="pre_arrival">Pre-Arrival</option>
                  <option value="room_preparation">Room Preparation</option>
                  <option value="maintenance">Maintenance</option>
                  <option value="guest_communication">Guest Communication</option>
                  <option value="follow_up">Follow-Up</option>
                  <option value="custom">Custom</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">Trigger</label>
                <select
                  value={formData.trigger}
                  onChange={(e) => setFormData({ ...formData, trigger: e.target.value as 'booking_created' | 'booking_confirmed' | 'check_in' | 'check_out' | 'manual' | 'scheduled' })}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                  disabled={!!workflow}
                >
                  <option value="booking_created">Booking Created</option>
                  <option value="booking_confirmed">Booking Confirmed</option>
                  <option value="check_in">Check In</option>
                  <option value="check_out">Check Out</option>
                  <option value="maintenance_request">Maintenance Request</option>
                  <option value="guest_message">Guest Message</option>
                  <option value="manual">Manual</option>
                  <option value="scheduled">Scheduled</option>
                </select>
              </div>
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">SLA (hours)</label>
              <input
                type="number"
                value={formData.sla_hours}
                onChange={(e) => setFormData({ ...formData, sla_hours: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                placeholder="e.g., 24"
              />
            </div>
          </div>

          {/* Workflow Steps */}
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-semibold text-gray-900">Workflow Steps</h3>
              <button
                type="button"
                onClick={addStep}
                className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors flex items-center gap-2"
              >
                <Plus className="w-4 h-4" />
                Add Step
              </button>
            </div>

            {steps.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                No steps added. Click "Add Step" to create workflow steps.
              </div>
            ) : (
              <div className="space-y-4">
                {steps.map((step, index) => (
                  <div key={index} className="border border-gray-200 rounded-lg p-4 bg-gray-50">
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex items-center gap-2">
                        <GripVertical className="w-5 h-5 text-gray-400" />
                        <span className="text-sm font-semibold text-gray-700">Step {index + 1}</span>
                      </div>
                      <button
                        type="button"
                        onClick={() => removeStep(index)}
                        className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-xs font-semibold text-gray-700 mb-1">Title *</label>
                        <input
                          type="text"
                          value={step.title}
                          onChange={(e) => updateStep(index, 'title', e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                          required
                        />
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-gray-700 mb-1">Task Type</label>
                        <select
                          value={step.task_type}
                          onChange={(e) => updateStep(index, 'task_type', e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        >
                          <option value="general">General</option>
                          <option value="room_cleaning">Room Cleaning</option>
                          <option value="maintenance">Maintenance</option>
                          <option value="guest_communication">Guest Communication</option>
                          <option value="check_in">Check In</option>
                          <option value="check_out">Check Out</option>
                        </select>
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-gray-700 mb-1">Priority</label>
                        <select
                          value={step.priority}
                          onChange={(e) => updateStep(index, 'priority', e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        >
                          <option value="low">Low</option>
                          <option value="medium">Medium</option>
                          <option value="high">High</option>
                          <option value="urgent">Urgent</option>
                        </select>
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-gray-700 mb-1">Duration (minutes)</label>
                        <input
                          type="number"
                          value={step.estimated_duration_minutes || ''}
                          onChange={(e) => updateStep(index, 'estimated_duration_minutes', parseInt(e.target.value) || 0)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        />
                      </div>
                    </div>
                    <div className="mt-4">
                      <label className="block text-xs font-semibold text-gray-700 mb-1">Description</label>
                      <textarea
                        value={step.description || ''}
                        onChange={(e) => updateStep(index, 'description', e.target.value)}
                        rows={2}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                      />
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Actions */}
          <div className="flex items-center justify-end gap-3 pt-4 border-t border-gray-200">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={loading}
              className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 flex items-center gap-2"
            >
              <Save className="w-4 h-4" />
              {loading ? 'Saving...' : workflow ? 'Update Workflow' : 'Create Workflow'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default WorkflowBuilder;

