import React, { useState } from 'react';
import {
  Plus,
  Edit,
  Trash2,
  Eye,
  CheckCircle2,
  Clock,
  XCircle,
} from 'lucide-react';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import EmptyState from '../../shared/components/EmptyState';
import { useAsync } from '../../shared/hooks/useAsync';
import workflowService, { Workflow } from '../../features/system/services/workflowService';
import WorkflowBuilder from '../../features/system/components/WorkflowBuilder';
import WorkflowDetailModal from '../../features/system/components/WorkflowDetailModal';

const WorkflowManagementPage: React.FC = () => {
  const [showBuilder, setShowBuilder] = useState(false);
  const [editingWorkflow, setEditingWorkflow] = useState<Workflow | null>(null);
  const [selectedWorkflow, setSelectedWorkflow] = useState<Workflow | null>(null);
  const [showDetail, setShowDetail] = useState(false);

  const { data: workflows, loading, execute: fetchWorkflows } = useAsync<Workflow[]>(
    () => workflowService.getWorkflows().then(r => r.data.data || []),
    { immediate: true }
  );

  const handleDelete = async (id: number) => {
    if (!window.confirm('Are you sure you want to delete this workflow?')) return;

    try {
      await workflowService.deleteWorkflow(id);
      toast.success('Workflow deleted successfully');
      fetchWorkflows();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to delete workflow');
    }
  };

  const handleEdit = (workflow: Workflow) => {
    setEditingWorkflow(workflow);
    setShowBuilder(true);
  };

  const handleView = async (workflow: Workflow) => {
    try {
      const response = await workflowService.getWorkflow(workflow.id);
      setSelectedWorkflow(response.data.data);
      setShowDetail(true);
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to load workflow details');
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'active':
        return <CheckCircle2 className="w-5 h-5 text-green-500" />;
      case 'inactive':
        return <Clock className="w-5 h-5 text-amber-500" />;
      default:
        return <XCircle className="w-5 h-5 text-gray-400" />;
    }
  };

  const getTypeColor = (type: string) => {
    const colors: Record<string, string> = {
      pre_arrival: 'bg-blue-100 text-blue-800 border-blue-200',
      room_preparation: 'bg-green-100 text-green-800 border-green-200',
      maintenance: 'bg-orange-100 text-orange-800 border-orange-200',
      guest_communication: 'bg-purple-100 text-purple-800 border-purple-200',
      follow_up: 'bg-pink-100 text-pink-800 border-pink-200',
      custom: 'bg-gray-100 text-gray-800 border-gray-200',
    };
    return colors[type] || colors.custom;
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6">
        {/* Header */}
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div>
              <h1 className="text-3xl font-bold text-gray-900 mb-2">Workflow Management</h1>
              <p className="text-gray-600">Create and manage automated workflows</p>
            </div>
            <button
              onClick={() => {
                setEditingWorkflow(null);
                setShowBuilder(true);
              }}
              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-5 h-5" />
              Create Workflow
            </button>
          </div>
        </div>

        {/* Workflows List */}
        {loading ? (
          <Loading fullScreen text="Loading workflows..." />
        ) : !workflows || !Array.isArray(workflows) || workflows.length === 0 ? (
          <div className="bg-white rounded-xl shadow-lg p-8 border border-gray-100">
            <EmptyState
              title="No workflows found"
              description="Create your first workflow to automate tasks"
              action={{
                label: 'Create Workflow',
                onClick: () => setShowBuilder(true),
              }}
            />
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {workflows.map((workflow) => (
              <div
                key={workflow.id}
                className="bg-white rounded-xl shadow-lg p-6 border border-gray-100 hover:shadow-xl transition-shadow"
              >
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-center gap-3">
                    {getStatusIcon(workflow.status)}
                    <div>
                      <h3 className="text-lg font-semibold text-gray-900">{workflow.name}</h3>
                      <span className={`px-2 py-1 rounded text-xs font-semibold border ${getTypeColor(workflow.workflow_type)}`}>
                        {workflow.workflow_type.replace('_', ' ')}
                      </span>
                    </div>
                  </div>
                </div>

                {workflow.description && (
                  <p className="text-sm text-gray-600 mb-4 line-clamp-2">{workflow.description}</p>
                )}

                <div className="space-y-2 mb-4">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-500">Trigger:</span>
                    <span className="font-medium text-gray-700">{workflow.trigger.replace('_', ' ')}</span>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-500">Steps:</span>
                    <span className="font-medium text-gray-700">{workflow.steps.length}</span>
                  </div>
                  {workflow.sla_hours && (
                    <div className="flex items-center justify-between text-sm">
                      <span className="text-gray-500">SLA:</span>
                      <span className="font-medium text-gray-700">{workflow.sla_hours} hours</span>
                    </div>
                  )}
                </div>

                <div className="flex items-center gap-2 pt-4 border-t border-gray-200">
                  <button
                    onClick={() => handleView(workflow)}
                    className="flex-1 px-3 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors flex items-center justify-center gap-2 text-sm"
                  >
                    <Eye className="w-4 h-4" />
                    View
                  </button>
                  <button
                    onClick={() => handleEdit(workflow)}
                    className="flex-1 px-3 py-2 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition-colors flex items-center justify-center gap-2 text-sm"
                  >
                    <Edit className="w-4 h-4" />
                    Edit
                  </button>
                  <button
                    onClick={() => handleDelete(workflow.id)}
                    className="px-3 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition-colors"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Workflow Builder Modal */}
      {showBuilder && (
        <WorkflowBuilder
          workflow={editingWorkflow}
          onClose={() => {
            setShowBuilder(false);
            setEditingWorkflow(null);
          }}
          onSuccess={() => {
            setShowBuilder(false);
            setEditingWorkflow(null);
            fetchWorkflows();
          }}
        />
      )}

      {/* Workflow Detail Modal */}
      {showDetail && selectedWorkflow && (
        <WorkflowDetailModal
          workflow={selectedWorkflow}
          onClose={() => {
            setShowDetail(false);
            setSelectedWorkflow(null);
          }}
        />
      )}
    </div>
  );
};

export default WorkflowManagementPage;

