import db from '../config/database.js';
import { v4 as uuidv4 } from 'uuid';

export const createCustomer = async (req, res) => {
  try {
    const {
      full_name,
      business_name,
      contact_number,
      address,
      job_category,
      description,
      assigned_to,
    } = req.body;

    const customerId = uuidv4();
    const resume_url = req.files?.resume ? `/uploads/${req.files.resume[0].filename}` : null;
    const assignedTo = assigned_to || null;

    await db.query(
      `INSERT INTO customers
         (id, full_name, business_name, contact_number, address,
          resume_url, job_category, description, assigned_to)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        customerId,
        full_name,
        business_name  || null,
        contact_number,
        address        || null,
        resume_url,
        job_category   || null,
        description    || null,
        assignedTo,
      ]
    );

    const [customer] = await db.query('SELECT * FROM customers WHERE id = ?', [customerId]);

    res.status(201).json({ message: 'Customer created successfully', customer: customer[0] });
  } catch (error) {
    console.error('Create customer error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};

export const getAllCustomers = async (req, res) => {
  try {
    const {
      search      = '',
      status      = 'all',
      category    = 'all',
      startDate   = '',
      endDate     = '',
      assigned_to = 'all',
      page        = 1,
      limit       = 20,
    } = req.query;

    const offset = (Number(page) - 1) * Number(limit);

    const params = [];
    const cond   = ['1=1'];

    if (status !== 'all') {
      cond.push('status = ?');
      params.push(status);
    }
    if (category !== 'all') {
      cond.push('job_category = ?');
      params.push(category);
    }
    if (search) {
      cond.push('(full_name LIKE ? OR contact_number LIKE ? OR business_name LIKE ?)');
      params.push(`%${search}%`, `%${search}%`, `%${search}%`);
    }
    if (startDate) {
      cond.push('DATE(created_at) >= ?');
      params.push(startDate);
    }
    if (endDate) {
      cond.push('DATE(created_at) <= ?');
      params.push(endDate);
    }
    if (assigned_to === 'unassigned') {
      cond.push('(assigned_to IS NULL OR assigned_to = "")');
    } else if (assigned_to !== 'all') {
      cond.push('assigned_to = ?');
      params.push(assigned_to);
    }

    const where = 'WHERE ' + cond.join(' AND ');

    const [[{ total }]] = await db.query(
      `SELECT COUNT(*) AS total FROM customers ${where}`,
      params
    );

    const [customers] = await db.query(
      `SELECT * FROM customers ${where} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
      [...params, Number(limit), offset]
    );

    const [[stats]] = await db.query(
      `SELECT
         COUNT(*)                              AS total,
         SUM(status = 'new')                   AS new,
         SUM(status = 'contacted')             AS contacted,
         SUM(status = 'meeting_scheduled')     AS meetings,
         SUM(status = 'converted')             AS converted,
         SUM(status = 'rejected')              AS rejected
       FROM customers`
    );

    res.json({
      customers,
      total,
      page: Number(page),
      stats: {
        total:     Number(stats.total     || 0),
        new:       Number(stats.new       || 0),
        contacted: Number(stats.contacted || 0),
        meetings:  Number(stats.meetings  || 0),
        converted: Number(stats.converted || 0),
        rejected:  Number(stats.rejected  || 0),
      },
    });
  } catch (error) {
    console.error('Get customers error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};

export const getCustomerById = async (req, res) => {
  try {
    const [customer] = await db.query(
      'SELECT * FROM customers WHERE id = ?',
      [req.params.id]
    );

    if (customer.length === 0) {
      return res.status(404).json({ error: 'Customer not found' });
    }

    res.json(customer[0]);
  } catch (error) {
    console.error('Get customer error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};

export const getAssignedCustomers = async (req, res) => {
  try {
    const {
      search    = '',
      status    = 'all',
      category  = 'all',
      startDate = '',
      endDate   = '',
      page      = 1,
      limit     = 10,
    } = req.query;

    const offset = (Number(page) - 1) * Number(limit);

    const params = [req.user.id];
    const cond   = ['assigned_to = ?'];

    if (status !== 'all') {
      cond.push('status = ?');
      params.push(status);
    }
    if (category !== 'all') {
      cond.push('job_category = ?');
      params.push(category);
    }
    if (search) {
      cond.push('(full_name LIKE ? OR contact_number LIKE ? OR business_name LIKE ?)');
      params.push(`%${search}%`, `%${search}%`, `%${search}%`);
    }
    if (startDate) {
      cond.push('DATE(created_at) >= ?');
      params.push(startDate);
    }
    if (endDate) {
      cond.push('DATE(created_at) <= ?');
      params.push(endDate);
    }

    const where = 'WHERE ' + cond.join(' AND ');

    const [[{ total }]] = await db.query(
      `SELECT COUNT(*) AS total FROM customers ${where}`,
      params
    );

    const [customers] = await db.query(
      `SELECT * FROM customers ${where} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
      [...params, Number(limit), offset]
    );

    const [[stats]] = await db.query(
      `SELECT
         COUNT(*)                              AS total,
         SUM(status = 'new')                   AS new,
         SUM(status = 'contacted')             AS contacted,
         SUM(status = 'meeting_scheduled')     AS meetings,
         SUM(status = 'converted')             AS converted,
         SUM(status = 'rejected')              AS rejected
       FROM customers
       WHERE assigned_to = ?`,
      [req.user.id]
    );

    res.json({
      customers,
      total,
      page: Number(page),
      stats: {
        total:     Number(stats.total     || 0),
        new:       Number(stats.new       || 0),
        contacted: Number(stats.contacted || 0),
        meetings:  Number(stats.meetings  || 0),
        converted: Number(stats.converted || 0),
        rejected:  Number(stats.rejected  || 0),
      },
    });
  } catch (error) {
    console.error('Get assigned customers error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};

export const assignCustomer = async (req, res) => {
  try {
    const { customerId, salesmanId } = req.body;

    await db.query(
      'UPDATE customers SET assigned_to = ?, status = ? WHERE id = ?',
      [salesmanId, 'contacted', customerId]
    );

    const [customer] = await db.query(
      'SELECT * FROM customers WHERE id = ?',
      [customerId]
    );

    res.json({ message: 'Customer assigned successfully', customer: customer[0] });
  } catch (error) {
    console.error('Assign customer error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};

export const updateCustomerStatus = async (req, res) => {
  try {
    const { status } = req.body;
    const customerId = req.params.id;

    await db.query(
      'UPDATE customers SET status = ? WHERE id = ?',
      [status, customerId]
    );

    const [customer] = await db.query(
      'SELECT * FROM customers WHERE id = ?',
      [customerId]
    );

    res.json({ message: 'Status updated successfully', customer: customer[0] });
  } catch (error) {
    console.error('Update status error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};