import { NextRequest, NextResponse } from 'next/server';
import dbConnect from '../../src/lib/mongodb';
import ProductColor from '../../src/models/ProductColor';
import Product from '../../src/models/Product';
import Color from '../../src/models/Color';
import Size from '../../src/models/Size';

export async function GET(request: NextRequest, context?: { params: Promise<any> }) {
  try {
    await dbConnect();

    const { searchParams } = new URL(request.url);
    const productId = searchParams.get('productId');
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '20');

    let query: any = {};

    if (productId) {
      query.product = productId;
    }

    const skip = (page - 1) * limit;

    const productColors = await ProductColor.find(query)
      .populate('product', 'name slug')
      .populate('color', 'name hexCode')
      .populate('size', 'name')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit);

    const total = await ProductColor.countDocuments(query);

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

  } catch (error: any) {
    console.error('Error fetching product colors:', error);
    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    await dbConnect();

    const body = await request.json();
    const {
      product,
      color,
      size,
      sku,
      price,
      comparePrice,
      inventory = 0,
      isActive = true
    } = body;

    // Validation
    if (!product || !color || !size || !sku || price === undefined || inventory === undefined) {
      return NextResponse.json(
        { success: false, error: 'Product, color, size, SKU, price, and inventory are required' },
        { status: 400 }
      );
    }

    // Validate product exists
    const productExists = await Product.findById(product);
    if (!productExists) {
      return NextResponse.json(
        { success: false, error: 'Product does not exist' },
        { status: 400 }
      );
    }

    // Validate color and size exist
    const colorExists = await Color.findById(color);
    const sizeExists = await Size.findById(size);

    if (!colorExists || !sizeExists) {
      return NextResponse.json(
        { success: false, error: 'Invalid color or size' },
        { status: 400 }
      );
    }

    const productColor = await ProductColor.create({
      product,
      color,
      size,
      sku: sku.toUpperCase(),
      price,
      comparePrice,
      inventory,
      isActive
    });

    const populatedProductColor = await ProductColor.findById(productColor._id)
      .populate('product', 'name slug')
      .populate('color', 'name hexCode')
      .populate('size', 'name');

    return NextResponse.json({
      success: true,
      data: populatedProductColor
    }, { status: 201 });

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

    if (error.code === 11000) {
      return NextResponse.json(
        { success: false, error: 'SKU already exists' },
        { status: 400 }
      );
    }

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

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: 'Product Color ID is required' },
        { status: 400 }
      );
    }

    const body = await request.json();
    const {
      price,
      comparePrice,
      inventory,
      isActive
    } = body;

    const productColor = await ProductColor.findByIdAndUpdate(
      id,
      {
        price,
        comparePrice,
        inventory,
        isActive
      },
      { new: true, runValidators: true }
    ).populate('product', 'name slug')
      .populate('color', 'name hexCode')
      .populate('size', 'name');

    if (!productColor) {
      return NextResponse.json(
        { success: false, error: 'Product Color not found' },
        { status: 404 }
      );
    }

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

  } catch (error: any) {
    console.error('Error updating product color:', error);
    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 }
    );
  }
}

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: 'Product Color ID is required' },
        { status: 400 }
      );
    }

    const productColor = await ProductColor.findByIdAndDelete(id);

    if (!productColor) {
      return NextResponse.json(
        { success: false, error: 'Product Color not found' },
        { status: 404 }
      );
    }

    // Also delete associated product images
    const ProductImage = require('@/models/ProductImage').default;
    await ProductImage.deleteMany({ productColor: id });

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

  } catch (error: any) {
    console.error('Error deleting product color:', error);
    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 }
    );
  }
}
