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

export async function GET(request: NextRequest) {
  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');

    let query: any = {};

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

    if (search) {
      query.name = { $regex: search, $options: 'i' };
    }

    const skip = (page - 1) * limit;

    const colors = await Color.find(query)
      .sort({ name: 1 })
      .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)
      } { $regex: search, $options: 'i' };
    }

    const skip = (page - 1) * limit;

    const colors = await Color.find(query)
      .sort({ name: 1 })
      .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 }
      );
    }

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

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

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

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

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

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

    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 }
    );
  }
}