import { NextRequest, NextResponse } from 'next/server';
import dbConnect from '../../src/lib/mongodb';
import GeneralSettings from '../../src/models/GeneralSettings';

// External upload server configuration
const UPLOAD_SERVER_URL = 'http://167.71.224.75:8700';
const UPLOAD_ENDPOINT = `${UPLOAD_SERVER_URL}/upload`;
const DELETE_ENDPOINT = `${UPLOAD_SERVER_URL}/delete`;

// Helper function to upload image to external server
async function uploadToExternalServer(file: File): Promise<string> {
  try {
    const formData = new FormData();
    formData.append('file', file);
    
    const response = await fetch(UPLOAD_ENDPOINT, {
      method: 'POST',
      body: formData,
    });
    
    if (!response.ok) {
      const errorText = await response.text();
      console.error('Upload failed:', response.status, errorText);
      throw new Error(`Upload failed: ${response.statusText}`);
    }
    
    const result = await response.json();
    
    if (result.success && result.url) {
      console.log('Image uploaded successfully:', result.url);
      const imageUrl = `https://quality-web-developer.com/dulhe_sahebimages/uploads/${result.filename}`;
      return imageUrl;
    } else if (result.success && result.filename) {
      // Construct URL if only filename is returned
      const imageUrl = `https://quality-web-developer.com/dulhe_sahebimages/uploads/${result.filename}`;
      return imageUrl;
    } else {
      throw new Error(result.error || 'Invalid response from upload server');
    }
  } catch (error) {
    console.error('Error uploading to external server:', error);
    throw new Error('Failed to upload image to external server');
  }
}

// Helper function to delete image from external server
async function deleteFromExternalServer(imageUrl: string): Promise<void> {
  try {
    // Don't delete if it's not from our external server
    if (!imageUrl.includes('quality-web-developer.com/dulhe_sahebimages')) {
      return;
    }
    
    // Extract filename from URL
    const filename = imageUrl.split('/').pop();
    if (!filename) return;
    
    const response = await fetch(DELETE_ENDPOINT, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ filename }),
    });
    
    if (!response.ok) {
      console.error('Failed to delete image from external server');
    } else {
      console.log('Image deleted successfully:', filename);
    }
  } catch (error) {
    console.error('Error deleting from external server:', error);
  }
}

// Helper function to validate file
function validateFile(file: File, fieldName: string): { isValid: boolean; error?: string } {
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/svg+xml'];
  if (!allowedTypes.includes(file.type)) {
    return { isValid: false, error: `Invalid file type for ${fieldName}. Only images are allowed.` };
  }
  
  const maxSize = 2 * 1024 * 1024; // 2MB
  if (file.size > maxSize) {
    return { isValid: false, error: `File too large for ${fieldName}. Maximum size is 2MB.` };
  }
  
  return { isValid: true };
}

// ✅ GET (Fetch settings)
export async function GET() {
  try {
    await dbConnect();

    // Assuming single settings document
    let settings = await GeneralSettings.findOne();

    // If not exists → create default
    if (!settings) {
      settings = await GeneralSettings.create({
        appName: 'My App',
        phoneNumber: '+1234567890',
        email: 'admin@example.com',
        location: 'Default Location',
        isActive: true
      });
    }

    return NextResponse.json({
      success: true,
      data: settings,
    });

  } catch (error: any) {
    console.error('Error fetching settings:', error);

    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 }
    );
  }
}

// ✅ UPDATE (Edit settings with image uploads)
export async function PUT(request: NextRequest, context?: { params: Promise<any> }) {
  try {
    await dbConnect();

    const contentType = request.headers.get('content-type') || '';

    let body: any = {};
    let uploadedImages: { [key: string]: string } = {};

    if (contentType.includes('multipart/form-data')) {
      // Handle form data with file uploads
      const formData = await request.formData();

      // Extract text fields
      const textFields = ['appName', 'phoneNumber', 'email', 'location', 'facebookLink', 'instagramLink','youtubeLink','printerestLink','statementContent','whatsappNumber', 'isActive'];
      textFields.forEach(field => {
        const value = formData.get(field);
        if (value !== null) {
          body[field] = field === 'isActive' ? value === 'true' : value;
        }
      });

      // Handle file uploads for images
      const imageFields = ['logo', 'footerLogo', 'favicon'];
      
      // First, get existing settings to check which images to delete
      const existingSettings = await GeneralSettings.findOne();
      
      for (const field of imageFields) {
        const file = formData.get(field) as File;
        
        // If new file is uploaded
        if (file && file.size > 0) {
          // Validate file
          const validation = validateFile(file, field);
          if (!validation.isValid) {
            return NextResponse.json(
              { success: false, error: validation.error },
              { status: 400 }
            );
          }

          // Delete old image from external server if exists
          if (existingSettings && existingSettings[field]) {
            await deleteFromExternalServer(existingSettings[field]);
          }

          // Upload new image to external server
          uploadedImages[field] = await uploadToExternalServer(file);
        }
      }
    } else {
      // Handle JSON data (backward compatibility)
      body = await request.json();
    }

    // Always keep only ONE settings document
    let settings = await GeneralSettings.findOne();

    if (!settings) {
      // Provide defaults for required fields if not provided
      const defaults = {
        appName: body.appName || 'My App',
        phoneNumber: body.phoneNumber || '+1234567890',
        email: body.email || 'admin@example.com',
        location: body.location || 'Default Location',
        youtubeLink: body.youtubeLink || '',
        printerestLink: body.printerestLink || '',
        statementContent: body.statementContent || '',
        whatsappNumber: body.whatsappNumber || '',
        isActive: body.isActive !== undefined ? body.isActive : true
      };
      settings = new GeneralSettings({ ...defaults, ...body, ...uploadedImages });
    } else {
      // Merge text fields and uploaded images
      Object.assign(settings, body);
      if (Object.keys(uploadedImages).length > 0) {
        Object.assign(settings, uploadedImages);
      }
    }

    await settings.save();

    return NextResponse.json({
      success: true,
      data: settings,
      message: 'Settings updated successfully',
    });

  } catch (error: any) {
    console.error('Error updating settings:', error);

    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 }
    );
  }
}

// ✅ DELETE specific image (optional endpoint)
export async function DELETE(request: NextRequest, context?: { params: Promise<any> }) {
  try {
    await dbConnect();
    
    const { searchParams } = new URL(request.url);
    const imageField = searchParams.get('field'); // 'logo', 'footerLogo', or 'favicon'
    
    if (!imageField || !['logo', 'footerLogo', 'favicon'].includes(imageField)) {
      return NextResponse.json(
        { success: false, error: 'Invalid image field' },
        { status: 400 }
      );
    }
    
    const settings = await GeneralSettings.findOne();
    if (!settings) {
      return NextResponse.json(
        { success: false, error: 'Settings not found' },
        { status: 404 }
      );
    }
    
    const imageUrl = settings[imageField];
    if (imageUrl) {
      // Delete from external server
      await deleteFromExternalServer(imageUrl);
      
      // Remove from database
      settings[imageField] = null;
      await settings.save();
    }
    
    return NextResponse.json({
      success: true,
      message: `${imageField} deleted successfully`,
      data: settings
    });
    
  } catch (error: any) {
    console.error('Error deleting image:', error);
    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 }
    );
  }
}