import { PrismaClient } from '@prisma/client';
import { v4 as uuidv4 } from 'uuid';

// Initialize Prisma client
const prisma = new PrismaClient();

export default defineEventHandler(async (event) => {
  try {
    // Parse the request body
    const body = await readBody(event);
    
    // Validate required fields
    if (!body.formName) {
      return {
        success: false,
        error: 'Form name is required'
      };
    }
    
    if (!Array.isArray(body.components)) {
      return {
        success: false,
        error: 'Components array is required'
      };
    }
    
    // Process and validate components
    const processedComponents = [];
    
    body.components.forEach((component, index) => {
      if (!component.type || !component.props) {
        console.warn(`Skipping invalid component at index ${index}:`, component);
        return;
      }
      
      // Process component properties based on type
      let processedProps = { ...component.props };
      
      // Ensure required grid properties
      if (!processedProps.width) {
        processedProps.width = '100%';
      }
      
      if (!processedProps.gridColumn) {
        processedProps.gridColumn = 'span 12';
      }
      
      // Handle special component types and ensure required properties
      switch (component.type) {
        case 'image-preview':
          processedProps = {
            label: processedProps.label || 'Image Preview',
            name: processedProps.name || `image_preview_${index + 1}`,
            help: processedProps.help || '',
            imageUrl: processedProps.imageUrl || 'https://placehold.co/600x400',
            altText: processedProps.altText || 'Preview image',
            caption: processedProps.caption || '',
            showZoom: processedProps.showZoom !== undefined ? processedProps.showZoom : true,
            showCaption: processedProps.showCaption !== undefined ? processedProps.showCaption : true,
            maxWidth: processedProps.maxWidth || '100%',
            height: processedProps.height || 'auto',
            ...processedProps
          };
          break;
          
        case 'repeating-group':
          processedProps = {
            label: processedProps.label || 'Repeating Group',
            name: processedProps.name || `repeating_group_${index + 1}`,
            help: processedProps.help || '',
            minItems: processedProps.minItems !== undefined ? processedProps.minItems : 1,
            maxItems: processedProps.maxItems !== undefined ? processedProps.maxItems : 10,
            buttonText: processedProps.buttonText || 'Add Item',
            removeText: processedProps.removeText || 'Remove',
            fields: processedProps.fields || [
              { type: 'text', name: 'field_1', label: 'Field 1', placeholder: 'Enter value' }
            ],
            ...processedProps
          };
          break;
          
        case 'dynamic-list':
          processedProps = {
            label: processedProps.label || 'Dynamic List',
            name: processedProps.name || `dynamic_list_${index + 1}`,
            help: processedProps.help || '',
            placeholder: processedProps.placeholder || 'Enter item',
            buttonText: processedProps.buttonText || 'Add Item',
            minItems: processedProps.minItems !== undefined ? processedProps.minItems : 0,
            maxItems: processedProps.maxItems !== undefined ? processedProps.maxItems : 20,
            defaultItems: Array.isArray(processedProps.defaultItems) ? processedProps.defaultItems : ['Item 1', 'Item 2'],
            ...processedProps
          };
          break;
          
        case 'info-display':
          processedProps = {
            title: processedProps.title || 'Information',
            name: processedProps.name || `info_display_${index + 1}`,
            help: processedProps.help || '',
            layout: processedProps.layout || 'vertical',
            showBorder: processedProps.showBorder !== undefined ? processedProps.showBorder : true,
            backgroundColor: processedProps.backgroundColor || '#f8fafc',
            fields: Array.isArray(processedProps.fields) ? processedProps.fields : [
              { label: 'Info Item', value: 'Value', key: 'item_1' }
            ],
            ...processedProps
          };
          break;
          
        case 'file':
          processedProps = {
            label: processedProps.label || 'File Upload',
            name: processedProps.name || `file_upload_${index + 1}`,
            help: processedProps.help || 'Upload a file',
            accept: processedProps.accept || '.pdf,.doc,.docx,.jpg,.jpeg,.png',
            ...processedProps
          };
          break;
          
        case 'heading':
          processedProps = {
            value: processedProps.value || 'Heading',
            level: processedProps.level || 2,
            ...processedProps
          };
          break;
          
        case 'paragraph':
          processedProps = {
            value: processedProps.value || 'Paragraph text',
            ...processedProps
          };
          break;
          
        case 'select':
        case 'radio':
        case 'checkbox':
          // Ensure options array exists
          if (!Array.isArray(processedProps.options) || processedProps.options.length === 0) {
            processedProps.options = [
              { label: 'Option 1', value: 'option_1' },
              { label: 'Option 2', value: 'option_2' }
            ];
          }
          break;
          
        default:
          // Basic properties for all other component types
          if (!processedProps.label && !['heading', 'paragraph', 'divider'].includes(component.type)) {
            processedProps.label = component.type.charAt(0).toUpperCase() + component.type.slice(1) + ' ' + (index + 1);
          }
          
          if (!processedProps.name && !['heading', 'paragraph', 'divider'].includes(component.type)) {
            processedProps.name = `${component.type}_${index + 1}`;
          }
          break;
      }
      
      // Add processed component
      processedComponents.push({
        type: component.type,
        props: processedProps
      });
    });
    
    // Create a new form in the database
    const form = await prisma.form.create({
      data: {
        formUUID: uuidv4(),
        formName: body.formName,
        formDescription: body.formDescription || null,
        formComponents: processedComponents,
        formStatus: 'active',
        formCreatedBy: body.createdBy || null, // In a real app, this would come from the authenticated user
        customScript: body.customScript || null,
        customCSS: body.customCSS || null,
        formEvents: body.formEvents || null,
        scriptMode: body.scriptMode || 'safe'
      }
    });
    
    // Create history entry for form creation
    if (form.formID) {
      try {
        await prisma.formHistory.create({
          data: {
            formHistoryFormID: form.formID,
            formHistoryAction: 'created_from_import',
            formHistoryData: {
              formName: form.formName,
              formDescription: form.formDescription,
              componentCount: processedComponents.length,
              importSource: 'json_import'
            },
            formHistorySavedBy: body.createdBy || null,
            formHistoryChangeDescription: 'Form created from JSON import'
          }
        });
      } catch (historyError) {
        console.warn('Failed to create history entry:', historyError);
        // Don't fail the import if history creation fails
      }
    }
    
    return {
      success: true,
      form,
      message: `Form "${form.formName}" imported successfully with ${processedComponents.length} components`
    };
  } catch (error) {
    console.error('Error importing form:', error);
    
    return {
      success: false,
      error: 'Failed to import form',
      details: process.env.NODE_ENV === 'development' ? error.message : undefined
    };
  }
}); 