import pool from '../../../../lib/db/db';
import { NextRequest, NextResponse } from 'next/server';
import { ResultSetHeader, RowDataPacket } from 'mysql2';
import bcrypt from 'bcryptjs';

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);

    const pageParam = parseInt(searchParams.get('page') || '1');
    const limitParam = parseInt(searchParams.get('limit') || '15');
    const search = searchParams.get('search')?.trim() || ''; // ✅ get search term

    const page = Number.isNaN(pageParam) || pageParam < 1 ? 1 : pageParam;
    const limit = Number.isNaN(limitParam) || limitParam < 1 ? 15 : limitParam;
    const skip = (page - 1) * limit;

    console.log('Searching for users with user_type: admin, search:', search);

    // Build search condition
    let whereClause = `user_type = ?`;
    let whereValues: any[] = ['admin'];

    if (search) {
      whereClause += ` AND (first_name LIKE ? OR last_name LIKE ? OR email LIKE ?)`;
      const searchPattern = `%${search}%`;
      whereValues.push(searchPattern, searchPattern, searchPattern);
    }

    // Count total
    const [countResult] = await pool.execute<RowDataPacket[]>(
      `SELECT COUNT(*) as totalItems FROM users WHERE ${whereClause}`,
      whereValues
    );
    const totalItems = countResult[0].totalItems;

    // Fetch admins
    const [admins] = await pool.execute<RowDataPacket[]>(
      `SELECT id, first_name, last_name, email, user_type, is_active, created_at
       FROM users 
       WHERE ${whereClause}
       ORDER BY created_at DESC 
       LIMIT ? OFFSET ?`,
      [...whereValues, limit, skip]
    );

    const users = admins.map((u) => ({
      ...u,
      createdAt: u.created_at ? new Date(u.created_at).toISOString() : null,
      created_at: u.created_at ? new Date(u.created_at).toISOString() : null,
    }));

    const totalPages = Math.max(1, Math.ceil(totalItems / limit));

    return NextResponse.json({
      success: true,
      users,
      meta: {
        page,
        limit,
        totalItems,
        totalPages,
        startIndex: skip,
        endIndex: skip + users.length,
        search: search || null,
      },
    });
  } catch (error) {
    console.error('❌ Error fetching admin users:', error);
    return NextResponse.json(
      { success: false, message: 'Server error' },
      { status: 500 }
    );
  }
}

export async function POST(request) {

  const connection = await pool.getConnection();

  try {
    const formData = await request.formData();

    // Extract form data
    const firstName = formData.get('first_name')?.toString().trim();
    const lastName = formData.get('last_name')?.toString().trim();
    const email = formData.get('email')?.toString().trim().toLowerCase();
    const password = formData.get('password')?.toString();
    const confirmPassword = formData.get('confirm_password')?.toString();
    const phone = formData.get('phone')?.toString().trim() || null;
    const city = formData.get('city')?.toString().trim() || null;
    const country = formData.get('country')?.toString().trim() || null;
    const postal = formData.get('postal')?.toString().trim() || null;
    const userGroup = formData.get('user_group')?.toString() || 'Administrator';
    const dob = formData.get('dob')?.toString() || null;
    const address = formData.get('address')?.toString().trim() || null;
    const active = formData.get('active')?.toString() === 'true';

    // Server-side validation
    if (!firstName || !lastName || !email || !password) {
      return NextResponse.json(
        { success: false, message: 'All required fields must be filled.' },
        { status: 400 }
      );
    }

    if (password.length < 6) {
      return NextResponse.json(
        { success: false, message: 'Password must be at least 6 characters long.' },
        { status: 400 }
      );
    }

    if (password !== confirmPassword) {
      return NextResponse.json(
        { success: false, message: 'Passwords do not match.' },
        { status: 400 }
      );
    }

    // Validate email format
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return NextResponse.json(
        { success: false, message: 'Please provide a valid email address.' },
        { status: 400 }
      );
    }

    // Check if email already exists
    const [existingUser] = await connection.query<RowDataPacket[]>(
      'SELECT id FROM users WHERE email = ?',
      [email]
    );

    if (existingUser.length > 0) {
      return NextResponse.json(
        { success: false, message: 'Email already exists.' },
        { status: 409 }
      );
    }

    // Hash password
    const saltRounds = 12;
    const hashedPassword = await bcrypt.hash(password, saltRounds);

    // Insert user into database
    const [result] = await connection.query<ResultSetHeader>(
      `INSERT INTO users (
        first_name, last_name, email, password, phone, city, country, 
        postal, dob, address, user_type,
        is_active, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
      [
        firstName,
        lastName,
        email,
        hashedPassword,
        phone,
        city,
        country,
        postal,
        dob,
        address,
        'admin',
        active
      ]
    );

    if (result.affectedRows === 1) {
      return NextResponse.json({
        success: true,
        message: 'Admin account created successfully.',
        userId: result.insertId
      });
    } else {
      throw new Error('Failed to create admin account');
    }

  } catch (error) {
    console.error('Admin registration error:', error);
    
    // Handle specific database errors
    if (error.code === 'ER_DUP_ENTRY') {
      return NextResponse.json(
        { success: false, message: 'Email already exists.' },
        { status: 409 }
      );
    }

    return NextResponse.json(
      { 
        success: false, 
        message: 'Internal server error. Please try again later.' 
      },
      { status: 500 }
    );
  }
}