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

// In your API route (app/api/colors/route.ts)
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 isActive = searchParams.get('isActive');
    const search = searchParams.get('search');
    const sort = searchParams.get('sort') || 'createdAt';
    const order = searchParams.get('order') || 'desc';

    let query: any = {};

    if (isActive !== null) {
      query.isActive = isActive === 'true';
    }

    if (search) {
      query.$or = [
        { name: { $regex: search, $options: "i" } },
        { hexCode: { $regex: search, $options: "i" } },
      ];
    }

    const skip = (page - 1) * limit;

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

    const colors = await Color.find(query)
      .sort(sortOptions)
      .skip(skip)
      .limit(limit);

    const total = await Color.countDocuments(query);

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

  } catch (error: any) {
    console.error('Error fetching 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 { name, hexCode, isActive = true } = body;

    if (!name || name.trim().length === 0) {
      return NextResponse.json(
        { success: false, error: 'Color name is required' },
        { status: 400 }
      );
    }
      const existing = await Color.findOne({
          $or: [
            { name: { $regex: `^${name}$`, $options: 'i' } }, // case insensitive name match
          ]
        });
    
        if (existing) {
          return NextResponse.json(
            { success: false, error: 'Color with this name already exists' },
            { status: 400 }
          );
        }

    if (!hexCode || !/^#[0-9A-F]{6}$/i.test(hexCode)) {
      return NextResponse.json(
        { success: false, error: 'Valid hex code is required (format: #RRGGBB)' },
        { status: 400 }
      );
    }

    const color = await Color.create({
      name: name.trim(),
      hexCode: hexCode.toUpperCase(),
      isActive
    });

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

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

    if (error.code === 11000) {
      return NextResponse.json(
        { success: false, error: 'Color with this name and hex code 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: 'Color ID is required' },
        { status: 400 }
      );
    }

    const body = await request.json();
    const { name, hexCode, isActive = true } = body;

    if (!name || name.trim().length === 0) {
      return NextResponse.json(
        { success: false, error: 'Color name is required' },
        { status: 400 }
      );
    }

    if (!hexCode || !/^#[0-9A-F]{6}$/i.test(hexCode)) {
      return NextResponse.json(
        { success: false, error: 'Valid hex code is required (format: #RRGGBB)' },
        { status: 400 }
      );
    }

    const color = await Color.findByIdAndUpdate(
      id,
      {
        name: name.trim(),
        hexCode: hexCode.toUpperCase(),
        isActive
      },
      { new: true, runValidators: true }
    );

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

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

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

    if (error.code === 11000) {
      return NextResponse.json(
        { success: false, error: 'Color with this name and hex code already exists' },
        { status: 400 }
      );
    }

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

    const color = await Color.findById(id);

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

    const isUsedInSku = await ProductSKU.exists({ color: id });
    if (isUsedInSku) {
      return NextResponse.json(
        { success: false, error: 'Cannot delete color because it is used in one or more product SKUs' },
        { status: 400 }
      );
    }

    await Color.findByIdAndDelete(id);

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

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