/**
 * Action Builder UI Component
 * Visual interface for creating and managing database actions
 */

import React, { useState, useEffect } from 'react';

interface SavedAction {
  id: string;
  name: string;
  description?: string;
  actionType: 'insert' | 'update' | 'delete' | 'api_call';
  actionTemplate: {
    sql?: string;
    url?: string;
    method?: string;
    headers?: Record<string, string>;
  };
  parameters: ActionParameter[];
  validationRules?: ValidationRule[];
  naturalLanguageTrigger?: string;
  confirmationRequired: boolean;
  confirmationMessage?: string;
  successMessage?: string;
  failureMessage?: string;
  requiresApproval: boolean;
  maxAffectedRows: number;
  connectionId: string;
  connectionName?: string;
}

interface ActionParameter {
  name: string;
  type: 'string' | 'number' | 'date' | 'boolean';
  required: boolean;
  defaultValue?: any;
  description?: string;
  validationRules?: ValidationRule[];
}

interface ValidationRule {
  type: 'required' | 'min' | 'max' | 'pattern' | 'enum';
  value?: any;
  message: string;
}

interface Connection {
  id: string;
  name: string;
  type: string;
}

export function ActionBuilder() {
  const [actions, setActions] = useState<SavedAction[]>([]);
  const [connections, setConnections] = useState<Connection[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingAction, setEditingAction] = useState<SavedAction | null>(null);

  const [formData, setFormData] = useState<Partial<SavedAction>>({
    name: '',
    description: '',
    actionType: 'update',
    actionTemplate: { sql: '' },
    parameters: [],
    naturalLanguageTrigger: '',
    confirmationRequired: true,
    confirmationMessage: 'هل أنت متأكد من إجراء هذا التغيير؟',
    successMessage: 'تم التنفيذ بنجاح.',
    failureMessage: 'حدث خطأ أثناء التنفيذ.',
    requiresApproval: false,
    maxAffectedRows: 1,
    connectionId: '',
  });

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setLoading(true);
    try {
      const [actionsRes, connectionsRes] = await Promise.all([
        fetch('/api/plugins/database-connector/actions'),
        fetch('/api/plugins/database-connector/connections'),
      ]);
      
      setActions((await actionsRes.json()).actions || []);
      setConnections((await connectionsRes.json()).connections || []);
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      const url = editingAction 
        ? `/api/plugins/database-connector/actions/${editingAction.id}`
        : '/api/plugins/database-connector/actions';
      
      await fetch(url, {
        method: editingAction ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });

      setShowForm(false);
      setEditingAction(null);
      resetForm();
      fetchData();
    } catch (error) {
      console.error('Failed to save action:', error);
    }
  };

  const handleEdit = (action: SavedAction) => {
    setEditingAction(action);
    setFormData(action);
    setShowForm(true);
  };

  const handleDelete = async (actionId: string) => {
    if (!confirm('هل أنت متأكد من حذف هذا الإجراء؟')) return;

    try {
      await fetch(`/api/plugins/database-connector/actions/${actionId}`, { method: 'DELETE' });
      fetchData();
    } catch (error) {
      console.error('Failed to delete action:', error);
    }
  };

  const resetForm = () => {
    setFormData({
      name: '',
      description: '',
      actionType: 'update',
      actionTemplate: { sql: '' },
      parameters: [],
      naturalLanguageTrigger: '',
      confirmationRequired: true,
      confirmationMessage: 'هل أنت متأكد من إجراء هذا التغيير؟',
      successMessage: 'تم التنفيذ بنجاح.',
      failureMessage: 'حدث خطأ أثناء التنفيذ.',
      requiresApproval: false,
      maxAffectedRows: 1,
      connectionId: '',
    });
  };

  const addParameter = () => {
    setFormData({
      ...formData,
      parameters: [
        ...(formData.parameters || []),
        { name: '', type: 'string', required: false },
      ],
    });
  };

  const updateParameter = (index: number, updates: Partial<ActionParameter>) => {
    const newParams = [...(formData.parameters || [])];
    newParams[index] = { ...newParams[index], ...updates };
    setFormData({ ...formData, parameters: newParams });
  };

  const removeParameter = (index: number) => {
    const newParams = formData.parameters?.filter((_, i) => i !== index) || [];
    setFormData({ ...formData, parameters: newParams });
  };

  const getActionTypeLabel = (type: string) => {
    switch (type) {
      case 'insert': return 'إضافة';
      case 'update': return 'تحديث';
      case 'delete': return 'حذف';
      case 'api_call': return 'استدعاء API';
      default: return type;
    }
  };

  const getActionTypeColor = (type: string) => {
    switch (type) {
      case 'insert': return 'bg-green-100 text-green-800';
      case 'update': return 'bg-blue-100 text-blue-800';
      case 'delete': return 'bg-red-100 text-red-800';
      case 'api_call': return 'bg-purple-100 text-purple-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="p-6" dir="rtl">
      {/* Header */}
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-2xl font-bold">⚡ منشئ الإجراءات</h1>
          <p className="text-muted-foreground">إنشاء وإدارة إجراءات قاعدة البيانات</p>
        </div>
        <button
          onClick={() => { setShowForm(true); resetForm(); setEditingAction(null); }}
          className="bg-primary text-primary-foreground px-4 py-2 rounded-lg flex items-center gap-2"
        >
          <span>+</span>
          <span>إجراء جديد</span>
        </button>
      </div>

      {/* Action Form Modal */}
      {showForm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-background rounded-lg w-full max-w-3xl max-h-[90vh] overflow-y-auto p-6">
            <h2 className="text-xl font-bold mb-4">
              {editingAction ? 'تعديل الإجراء' : 'إجراء جديد'}
            </h2>

            <form onSubmit={handleSubmit} className="space-y-4">
              {/* Basic Info */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium mb-1">اسم الإجراء</label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    className="w-full border rounded-lg px-3 py-2"
                    placeholder="مثال: تحديث العنوان"
                    required
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1">نوع الإجراء</label>
                  <select
                    value={formData.actionType}
                    onChange={(e) => setFormData({ ...formData, actionType: e.target.value as any })}
                    className="w-full border rounded-lg px-3 py-2"
                    required
                  >
                    <option value="update">تحديث (UPDATE)</option>
                    <option value="insert">إضافة (INSERT)</option>
                    <option value="delete">حذف (DELETE)</option>
                    <option value="api_call">استدعاء API</option>
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium mb-1">الاتصال</label>
                  <select
                    value={formData.connectionId}
                    onChange={(e) => setFormData({ ...formData, connectionId: e.target.value })}
                    className="w-full border rounded-lg px-3 py-2"
                    required
                  >
                    <option value="">اختر الاتصال</option>
                    {connections.map((conn) => (
                      <option key={conn.id} value={conn.id}>{conn.name}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1">الوصف</label>
                  <input
                    type="text"
                    value={formData.description}
                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                    className="w-full border rounded-lg px-3 py-2"
                    placeholder="وصف مختصر"
                  />
                </div>
              </div>

              {/* SQL/API Template */}
              {formData.actionType === 'api_call' ? (
                <div className="space-y-3">
                  <div className="grid grid-cols-3 gap-3">
                    <div>
                      <label className="block text-sm font-medium mb-1">Method</label>
                      <select
                        value={formData.actionTemplate?.method || 'POST'}
                        onChange={(e) => setFormData({
                          ...formData,
                          actionTemplate: { ...formData.actionTemplate, method: e.target.value }
                        })}
                        className="w-full border rounded-lg px-3 py-2"
                      >
                        <option value="POST">POST</option>
                        <option value="PUT">PUT</option>
                        <option value="PATCH">PATCH</option>
                        <option value="DELETE">DELETE</option>
                      </select>
                    </div>
                    <div className="col-span-2">
                      <label className="block text-sm font-medium mb-1">URL</label>
                      <input
                        type="url"
                        value={formData.actionTemplate?.url || ''}
                        onChange={(e) => setFormData({
                          ...formData,
                          actionTemplate: { ...formData.actionTemplate, url: e.target.value }
                        })}
                        className="w-full border rounded-lg px-3 py-2"
                        placeholder="https://api.example.com/endpoint"
                      />
                    </div>
                  </div>
                </div>
              ) : (
                <div>
                  <label className="block text-sm font-medium mb-1">قالب SQL</label>
                  <textarea
                    value={formData.actionTemplate?.sql || ''}
                    onChange={(e) => setFormData({
                      ...formData,
                      actionTemplate: { ...formData.actionTemplate, sql: e.target.value }
                    })}
                    className="w-full border rounded-lg px-3 py-2 font-mono text-sm h-24"
                    placeholder={`UPDATE customers
SET address = {{new_address}}
WHERE id = {{customer_id}}`}
                    required
                  />
                </div>
              )}

              {/* Parameters */}
              <div>
                <div className="flex justify-between items-center mb-2">
                  <label className="text-sm font-medium">المعاملات</label>
                  <button type="button" onClick={addParameter} className="text-sm text-primary hover:underline">
                    + إضافة معامل
                  </button>
                </div>
                
                {formData.parameters?.map((param, index) => (
                  <div key={index} className="flex gap-2 mb-2 items-center">
                    <input
                      type="text"
                      value={param.name}
                      onChange={(e) => updateParameter(index, { name: e.target.value })}
                      className="flex-1 border rounded px-2 py-1 text-sm"
                      placeholder="اسم المعامل"
                    />
                    <select
                      value={param.type}
                      onChange={(e) => updateParameter(index, { type: e.target.value as any })}
                      className="border rounded px-2 py-1 text-sm"
                    >
                      <option value="string">نص</option>
                      <option value="number">رقم</option>
                      <option value="date">تاريخ</option>
                    </select>
                    <label className="flex items-center gap-1 text-sm">
                      <input
                        type="checkbox"
                        checked={param.required}
                        onChange={(e) => updateParameter(index, { required: e.target.checked })}
                      />
                      مطلوب
                    </label>
                    <button type="button" onClick={() => removeParameter(index)} className="text-red-500">✕</button>
                  </div>
                ))}
              </div>

              {/* Natural Language Trigger */}
              <div>
                <label className="block text-sm font-medium mb-1">محفز اللغة الطبيعية</label>
                <input
                  type="text"
                  value={formData.naturalLanguageTrigger}
                  onChange={(e) => setFormData({ ...formData, naturalLanguageTrigger: e.target.value })}
                  className="w-full border rounded-lg px-3 py-2"
                  placeholder='مثال: "غيّر عنواني" أو "حدّث رقمي"'
                />
              </div>

              {/* Safety Settings */}
              <div className="border rounded-lg p-4 bg-yellow-50 space-y-3">
                <h4 className="font-medium text-yellow-800">⚠️ إعدادات الأمان</h4>
                
                <div className="flex items-center gap-3">
                  <label className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      checked={formData.confirmationRequired}
                      onChange={(e) => setFormData({ ...formData, confirmationRequired: e.target.checked })}
                    />
                    <span className="text-sm">طلب تأكيد من العميل</span>
                  </label>
                  
                  <label className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      checked={formData.requiresApproval}
                      onChange={(e) => setFormData({ ...formData, requiresApproval: e.target.checked })}
                    />
                    <span className="text-sm">يتطلب موافقة مسؤول</span>
                  </label>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm mb-1">أقصى عدد صفوف متأثرة</label>
                    <input
                      type="number"
                      value={formData.maxAffectedRows}
                      onChange={(e) => setFormData({ ...formData, maxAffectedRows: parseInt(e.target.value) })}
                      className="w-full border rounded px-3 py-1"
                      min="1"
                      max="100"
                    />
                  </div>
                  <div>
                    <label className="block text-sm mb-1">رسالة التأكيد</label>
                    <input
                      type="text"
                      value={formData.confirmationMessage}
                      onChange={(e) => setFormData({ ...formData, confirmationMessage: e.target.value })}
                      className="w-full border rounded px-3 py-1"
                    />
                  </div>
                </div>
              </div>

              {/* Messages */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium mb-1">رسالة النجاح</label>
                  <input
                    type="text"
                    value={formData.successMessage}
                    onChange={(e) => setFormData({ ...formData, successMessage: e.target.value })}
                    className="w-full border rounded-lg px-3 py-2"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1">رسالة الفشل</label>
                  <input
                    type="text"
                    value={formData.failureMessage}
                    onChange={(e) => setFormData({ ...formData, failureMessage: e.target.value })}
                    className="w-full border rounded-lg px-3 py-2"
                  />
                </div>
              </div>

              {/* Form Actions */}
              <div className="flex justify-end gap-3 pt-4 border-t">
                <button type="button" onClick={() => setShowForm(false)} className="px-4 py-2 border rounded-lg">
                  إلغاء
                </button>
                <button type="submit" className="bg-primary text-primary-foreground px-4 py-2 rounded-lg">
                  {editingAction ? 'حفظ التعديلات' : 'إنشاء الإجراء'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Actions List */}
      <div className="grid gap-4">
        {actions.length === 0 ? (
          <div className="text-center py-12 bg-muted/50 rounded-lg">
            <span className="text-4xl mb-4 block">⚡</span>
            <p className="text-muted-foreground">لا توجد إجراءات محفوظة</p>
            <button onClick={() => { setShowForm(true); resetForm(); }} className="mt-4 text-primary hover:underline">
              إنشاء أول إجراء
            </button>
          </div>
        ) : (
          actions.map((action) => (
            <div key={action.id} className="bg-card border rounded-lg p-4">
              <div className="flex justify-between items-start">
                <div>
                  <div className="flex items-center gap-2">
                    <h3 className="font-semibold">{action.name}</h3>
                    <span className={`text-xs px-2 py-0.5 rounded ${getActionTypeColor(action.actionType)}`}>
                      {getActionTypeLabel(action.actionType)}
                    </span>
                  </div>
                  {action.description && <p className="text-sm text-muted-foreground">{action.description}</p>}
                  <div className="flex gap-2 mt-2 flex-wrap">
                    {action.confirmationRequired && (
                      <span className="text-xs bg-yellow-100 text-yellow-800 px-2 py-1 rounded">يتطلب تأكيد</span>
                    )}
                    {action.requiresApproval && (
                      <span className="text-xs bg-red-100 text-red-800 px-2 py-1 rounded">يتطلب موافقة</span>
                    )}
                    {action.naturalLanguageTrigger && (
                      <span className="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded">
                        "{action.naturalLanguageTrigger}"
                      </span>
                    )}
                  </div>
                </div>
                <div className="flex gap-2">
                  <button onClick={() => handleEdit(action)} className="text-sm text-primary hover:underline">تعديل</button>
                  <button onClick={() => handleDelete(action.id)} className="text-sm text-red-500 hover:underline">حذف</button>
                </div>
              </div>
              
              <div className="mt-3 bg-muted rounded p-2 font-mono text-xs overflow-x-auto">
                {action.actionTemplate?.sql || action.actionTemplate?.url}
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

export default ActionBuilder;
