// app/api/sliders/route.ts
import { NextRequest, NextResponse } from 'next/server';
import dbConnect from '../../src/lib/mongodb';
import Slider from '../../src/models/Slider';

// 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 single 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) {
      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 {
    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);
  }
}

// ✅ GET (Fetch sliders with pagination and sorting)
export async function GET(request: NextRequest, context?: { params: Promise<any> }) {
  try {
    await dbConnect();

    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');
    const search = searchParams.get('search');
    const status = searchParams.get('status');
    const sort = searchParams.get('sort') || 'order';
    const order = searchParams.get('order') || 'asc';

    // Build query
    let query: any = {};

    if (search) {
      query.$or = [
        { title: { $regex: search, $options: 'i' } },
        { sub_title: { $regex: search, $options: 'i' } },
        { description: { $regex: search, $options: 'i' } }
      ];
    }

    if (status !== null && status !== undefined && status !== 'all') {
      query.status = status === 'true';
    }

    const skip = (page - 1) * limit;

    // Create sort object
    const sortOptions: any = {};
    if (search) {
      sortOptions.title = 1;
    }
    else if (sort === 'order') {
      sortOptions.order = order === 'asc' ? 1 : -1;
    } else if (sort === 'createdAt') {
      sortOptions.createdAt = order === 'asc' ? 1 : -1;
    } else if (sort === 'title') {
      sortOptions.title = order === 'asc' ? 1 : -1;
    } else if (sort === 'status') {
      sortOptions.status = order === 'asc' ? 1 : -1;
    } else {
      sortOptions.order = 1;
    }

    // Fetch sliders
    const sliders = await Slider.find(query)
      .sort(sortOptions)
      .skip(skip)
      .limit(limit);

    const total = await Slider.countDocuments(query);

    return NextResponse.json({
      success: true,
      data: sliders,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit)
      }
    });

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

    return NextResponse.json(
      {
        success: false,
        error: error.message || 'Failed to fetch sliders'
      },
      { status: 500 }
    );
  }
}

// ✅ POST (Create slider)
export async function POST(request: NextRequest) {
  try {
    await dbConnect();

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

    if (!contentType.includes('multipart/form-data')) {
      return NextResponse.json(
        { success: false, error: 'Content-Type must be multipart/form-data' },
        { status: 400 }
      );
    }

    const formData = await request.formData();
    const title = formData.get('title') as string;
    const sub_title = formData.get('sub_title') as string;
    const description = formData.get('description') as string;
    const link = formData.get('link') as string;
    const button_text = formData.get('button_text') as string;
    const order = parseInt(formData.get('order') as string) || 0;
    const status = formData.get('status') === 'true';
    const image = formData.get('image') as File;

    // Validation
    if (!title?.trim()) {
      return NextResponse.json(
        { success: false, error: 'Slider title is required' },
        { status: 400 }
      );
    }

    if (!sub_title?.trim()) {
      return NextResponse.json(
        { success: false, error: 'Sub title is required' },
        { status: 400 }
      );
    }

    if (!description?.trim()) {
      return NextResponse.json(
        { success: false, error: 'Description is required' },
        { status: 400 }
      );
    }

    if (!image) {
      return NextResponse.json(
        { success: false, error: 'Slider image is required' },
        { status: 400 }
      );
    }

    // Validate image file
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'];
    if (!allowedTypes.includes(image.type)) {
      return NextResponse.json(
        { success: false, error: 'Invalid file type. Only JPEG, PNG, WebP, and GIF are allowed.' },
        { status: 400 }
      );
    }

    // Validate file size (5MB max)
    const maxSize = 5 * 1024 * 1024;
    if (image.size > maxSize) {
      return NextResponse.json(
        { success: false, error: 'File too large. Maximum size is 5MB.' },
        { status: 400 }
      );
    }

    // Upload image to external server
    let imageUrl = '';
    try {
      imageUrl = await uploadToExternalServer(image);
    } catch (uploadError) {
      console.error('Upload error:', uploadError);
      return NextResponse.json(
        { success: false, error: 'Failed to upload image to server' },
        { status: 500 }
      );
    }

    // Create slider
    const slider = await Slider.create({
      title: title.trim(),
      sub_title: sub_title.trim(),
      description: description.trim(),
      image: imageUrl,
      link: link?.trim() || '',
      button_text: button_text?.trim() || 'Learn More',
      order,
      status
    });

    return NextResponse.json({
      success: true,
      data: slider,
      message: 'Slider created successfully'
    });

  } catch (error: any) {
    console.error('Error creating slider:', error);

    return NextResponse.json(
      { success: false, error: error.message || 'Failed to create slider' },
      { status: 500 }
    );
  }
}

// ✅ PUT (Update slider)
export async function PUT(request: NextRequest, context?: { params: Promise<any> }) {
  try {
    await dbConnect();

    const url = new URL(request.url);
    const id = url.pathname.split('/').pop();
    
    if (!id) {
      return NextResponse.json(
        { success: false, error: 'Slider ID is required' },
        { status: 400 }
      );
    }

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

    if (!contentType.includes('multipart/form-data')) {
      return NextResponse.json(
        { success: false, error: 'Content-Type must be multipart/form-data' },
        { status: 400 }
      );
    }

    const formData = await request.formData();
    const title = formData.get('title') as string;
    const sub_title = formData.get('sub_title') as string;
    const description = formData.get('description') as string;
    const link = formData.get('link') as string;
    const button_text = formData.get('button_text') as string;
    const order = parseInt(formData.get('order') as string);
    const status = formData.get('status') === 'true';
    const image = formData.get('image') as File | null;

    // Check if slider exists
    const existingSlider = await Slider.findById(id);
    if (!existingSlider) {
      return NextResponse.json(
        { success: false, error: 'Slider not found' },
        { status: 404 }
      );
    }

    // Validation
    if (!title?.trim()) {
      return NextResponse.json(
        { success: false, error: 'Slider title is required' },
        { status: 400 }
      );
    }

    if (!sub_title?.trim()) {
      return NextResponse.json(
        { success: false, error: 'Sub title is required' },
        { status: 400 }
      );
    }

    if (!description?.trim()) {
      return NextResponse.json(
        { success: false, error: 'Description is required' },
        { status: 400 }
      );
    }

    let imageUrl = existingSlider.image;

    // Handle new image upload
    if (image && image.size > 0) {
      // Validate image file
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'];
      if (!allowedTypes.includes(image.type)) {
        return NextResponse.json(
          { success: false, error: 'Invalid file type. Only JPEG, PNG, WebP, and GIF are allowed.' },
          { status: 400 }
        );
      }

      // Validate file size
      const maxSize = 5 * 1024 * 1024;
      if (image.size > maxSize) {
        return NextResponse.json(
          { success: false, error: 'File too large. Maximum size is 5MB.' },
          { status: 400 }
        );
      }

      // Delete old image from external server
      if (existingSlider.image && existingSlider.image.includes('quality-web-developer.com')) {
        await deleteFromExternalServer(existingSlider.image);
      }
      
      // Upload new image
      try {
        imageUrl = await uploadToExternalServer(image);
      } catch (uploadError) {
        console.error('Upload error:', uploadError);
        return NextResponse.json(
          { success: false, error: 'Failed to upload image to server' },
          { status: 500 }
        );
      }
    }

    // Update slider
    const updatedSlider = await Slider.findByIdAndUpdate(
      id,
      {
        title: title.trim(),
        sub_title: sub_title.trim(),
        description: description.trim(),
        image: imageUrl,
        link: link?.trim() || '',
        button_text: button_text?.trim() || 'Learn More',
        order: order || 0,
        status
      },
      { new: true, runValidators: true }
    );

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

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

    return NextResponse.json(
      { success: false, error: error.message || 'Failed to update slider' },
      { status: 500 }
    );
  }
}

// ✅ DELETE (Delete slider)
export async function DELETE(request: NextRequest, context?: { params: Promise<any> }) {
  try {
    await dbConnect();

    const url = new URL(request.url);
    const id = url.pathname.split('/').pop();

    if (!id) {
      return NextResponse.json(
        { success: false, error: 'Slider ID is required' },
        { status: 400 }
      );
    }

    // Check if slider exists
    const slider = await Slider.findById(id);
    if (!slider) {
      return NextResponse.json(
        { success: false, error: 'Slider not found' },
        { status: 404 }
      );
    }

    // Delete image from external server
    if (slider.image && slider.image.includes('quality-web-developer.com')) {
      await deleteFromExternalServer(slider.image);
    }

    await Slider.findByIdAndDelete(id);

    return NextResponse.json({
      success: true,
      message: 'Slider deleted successfully'
    });

  } catch (error: any) {
    console.error('Error deleting slider:', error);
    return NextResponse.json(
      { success: false, error: error.message || 'Failed to delete slider' },
      { status: 500 }
    );
  }
}

// ✅ PATCH (Update slider order - for drag and drop reordering)
export async function PATCH(request: NextRequest) {
  try {
    await dbConnect();

    const body = await request.json();
    const { sliders } = body; // Array of { id, order }

    if (!sliders || !Array.isArray(sliders)) {
      return NextResponse.json(
        { success: false, error: 'Invalid data format' },
        { status: 400 }
      );
    }

    // Update each slider's order
    const updatePromises = sliders.map((item: { id: string; order: number }) =>
      Slider.findByIdAndUpdate(item.id, { order: item.order }, { new: true })
    );

    await Promise.all(updatePromises);

    return NextResponse.json({
      success: true,
      message: 'Slider order updated successfully'
    });

  } catch (error: any) {
    console.error('Error updating slider order:', error);
    return NextResponse.json(
      { success: false, error: error.message || 'Failed to update slider order' },
      { status: 500 }
    );
  }
}

// ✅ GET single slider by ID (optional - separate endpoint)
export async function getSliderById(id: string) {
  try {
    await dbConnect();
    const slider = await Slider.findById(id);
    
    if (!slider) {
      return null;
    }
    
    return slider;
  } catch (error) {
    console.error('Error fetching slider by ID:', error);
    return null;
  }
}