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

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 category = searchParams.get('category');
    const subcategory = searchParams.get('subcategory');
    const isActive = searchParams.get('isActive');
    const isFeatured = searchParams.get('isFeatured');
    const search = searchParams.get('search');

    let query: any = {};

    if (category) {
      query.category = category;
    }

    if (subcategory) {
      query.subcategory = subcategory;
    }

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

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

    if (search) {
      query.$text = { $search: search };
    }

    const skip = (page - 1) * limit;

    const products = await Product.find(query)
      .populate('category', 'name slug')
      .populate('subcategory', 'name slug')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit);

    const total = await Product.countDocuments(query);

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

  } catch (error: any) {
    console.error('Error fetching products:', 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,
      description,
      shortDescription,
      category,
      subcategory,
      brand,
      tags = [],
      isActive = true,
      isFeatured = false,
      weight,
      dimensions,
      seoTitle,
      seoDescription
    } = body;

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

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

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

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

    // Validate subcategory if provided
    if (subcategory) {
      const subcategoryExists = await Category.findById(subcategory);
      if (!subcategoryExists) {
        return NextResponse.json(
          { success: false, error: 'Selected subcategory does not exist' },
          { status: 400 }
        );
      }
    }

    const product = await Product.create({
      name: name.trim(),
      description: description.trim(),
      shortDescription: shortDescription?.trim(),
      category,
      subcategory,
      brand: brand?.trim(),
      tags: tags.map((tag: string) => tag.trim().toLowerCase()),
      isActive,
      isFeatured,
      weight,
      dimensions,
      seoTitle: seoTitle?.trim(),
      seoDescription: seoDescription?.trim()
    });

    const populatedProduct = await Product.findById(product._id)
      .populate('category', 'name slug')
      .populate('subcategory', 'name slug');

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

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

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

    const body = await request.json();
    const {
      name,
      description,
      shortDescription,
      category,
      subcategory,
      brand,
      tags = [],
      isActive = true,
      isFeatured = false,
      weight,
      dimensions,
      seoTitle,
      seoDescription
    } = body;

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

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

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

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

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

    // Validate subcategory if provided
    if (subcategory) {
      const subcategoryExists = await Category.findById(subcategory);
      if (!subcategoryExists) {
        return NextResponse.json(
          { success: false, error: 'Selected subcategory does not exist' },
          { status: 400 }
        );
      }
    }

    const updatedProduct = await Product.findByIdAndUpdate(
      id,
      {
        name: name.trim(),
        description: description.trim(),
        shortDescription: shortDescription?.trim(),
        category,
        subcategory,
        brand: brand?.trim(),
        tags: tags.map((tag: string) => tag.trim().toLowerCase()),
        isActive,
        isFeatured,
        weight,
        dimensions,
        seoTitle: seoTitle?.trim(),
        seoDescription: seoDescription?.trim()
      },
      { new: true, runValidators: true }
    )
    .populate('category', 'name slug')
    .populate('subcategory', 'name slug');

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

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

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

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

    // Delete associated product colors and images
    const ProductColor = require('@/models/ProductColor').default;
    const ProductImage = require('@/models/ProductImage').default;
    
    const productColors = await ProductColor.find({ product: id });
    const productColorIds = productColors.map((pc: any) => pc._id);
    
    // Delete all product images associated with these colors
    await ProductImage.deleteMany({ productColor: { $in: productColorIds } });
    
    // Delete all product colors for this product
    await ProductColor.deleteMany({ product: id });

    // Delete the product
    await Product.findByIdAndDelete(id);

    return NextResponse.json({
      success: true,
      message: 'Product and all associated data deleted successfully'
    });

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