const mongoose = require("mongoose");
const Task = require("../../models/taskModel");
const Customer = require("../../models/admin/customerModel");

const getMobileDashboard = async (req, res) => {
  try {
    const userId = req.user._id;
    const orgId = req.user.orgId;
    const now = new Date();
    const [stats] = await Task.aggregate([
      {
        $match: {
          orgId: new mongoose.Types.ObjectId(orgId),
          assignedTo: new mongoose.Types.ObjectId(userId),
          isDeleted: false
        }
      },
      {
        $group: {
          _id: null,
          totalTasks: { $sum: 1 },
          completed: {
            $sum: { $cond: [{ $eq: ["$status", "Completed"] }, 1, 0] }
          },
          cancelled: {
            $sum: {
              $cond: [
                { $in: ["$status", ["Closed", "Rejected"]] },
                1,
                0
              ]
            }

          },
          tatAlerts: {
            $sum: {
              $cond: [
                {
                  $and: [
                    { $lt: ["$dueDate", now] },
                    { $ne: ["$status", "Completed"] }
                  ]
                },
                1,
                0
              ]
            }
          }
        }
      }
    ]);

    // Leaderboard (top performer in org)
    const leaderboard = await Task.aggregate([
      {
        $match: {
          orgId: new mongoose.Types.ObjectId(orgId),
          status: "Completed",
          isDeleted: false
        }
      },
      {
        $group: {
          _id: "$assignedTo",
          completedCount: { $sum: 1 }
        }
      },
      { $sort: { completedCount: -1 } },
      { $limit: 1 }
    ]);

    return res.json({
      success: true,
      data: {
        summary: stats || {
          totalTasks: 0,
          completed: 0,
          cancelled: 0,
          tatAlerts: 0
        },
        leaderboard: leaderboard.length
          ? leaderboard[0]
          : null
      }
    });
  } catch (err) {
    console.error("Mobile Dashboard Error:", err);
    return res.status(500).json({
      success: false,
      message: "Failed to load dashboard"
    });
  }
};



const maskPhone = (phone = "") => {
  if (phone.length !== 10) return phone;
  return phone.slice(0, 2) + "*****" + phone.slice(-3);
};

// const getAgentTasksMobile = async (req, res) => {
//   try {
//     const agentId = req.user._id;
//     const orgId = req.user.orgId;

//     let { page = 1, limit = 10, search = "" } = req.query;
//     page = parseInt(page);
//     limit = parseInt(limit);

//     const skip = (page - 1) * limit;

//     const query = {
//       assignedTo: agentId,
//       orgId,
//       isDeleted: false,
//     };

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

//     // const [tasks, total] = await Promise.all([
//     //   Task.find(query)
//     //     .sort({ createdAt: -1 })
//     //     .skip(skip)
//     //     .limit(limit)
//     //     .select(
//     //       "customer serviceName status createdAt taskName"
//     //     )
//     //     .lean(),
//     //   Task.countDocuments(query),
//     // ]);

//     const tasks = await Task.find({ isDeleted : false})

//     const formatted = tasks.map((task) => ({
//       taskId: task._id,
//       customerName: task.customer?.name || "--",
//       phone: maskPhone(task.customer?.phone),
//       address: task.customer?.address || "--",
//       service: task.serviceName,
//       status: task.status,
//     }));

//     return res.status(200).json({
//       success: true,
//       page,
//       limit,
//       // total,
//       // totalPages: Math.ceil(total / limit),
//       data: formatted,
//     });
//   } catch (err) {
//     console.error("MOBILE TASK LIST ERROR:", err);
//     return res.status(500).json({
//       success: false,
//       message: "Failed to fetch tasks",
//     });
//   }
// };
const getAgentTasksMobile = async (req, res) => {
  try {
    const agentId = req.user._id;
    const orgId = req.user.orgId;

    let { page = 1, limit = 10, search = "" } = req.query;
    page = parseInt(page);
    limit = parseInt(limit);

    const skip = (page - 1) * limit;
    const query = {
      assignedTo: agentId,        //  agent specific
      orgId,
      // status: "assigned",         //  ONLY assigned tasks
      isDeleted: false,
    };

    const [tasks, total] = await Promise.all([
      Task.find(query)
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(limit)
        // .select("customer serviceName status createdAt")
        .lean(),
      Task.countDocuments(query),
    ]);

    const formatted = tasks.map((task) => ({
      taskId: task._id,
      customerName: task.customer?.name || "--",
      phone: maskPhone(task.customer?.phone),
      address: task.customer?.address || "--",
      service: task.serviceName,
      status: task.status,
    }));

    return res.status(200).json({
      success: true,
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit),
      data: formatted,
    });
  } catch (err) {
    console.error("MOBILE TASK LIST ERROR:", err);
    return res.status(500).json({
      success: false,
      message: "Failed to fetch tasks",
    });
  }
};


const acceptTask = async (req, res) => {
  try {
    const agentId = req.user._id;
    const { id: taskId } = req.params;

    const task = await Task.findOne({
      _id: taskId,
      assignedTo: agentId,
      isDeleted: false,
    });

    if (!task) {
      return res.status(404).json({
        success: false,
        message: "Task not found or not assigned to you",
      });
    }

    if (task.status !== "Assigned") {
      return res.status(409).json({
        success: false,
        message: `Task cannot be accepted. Current status: ${task.status}`,
      });
    }


    const previousStatus = task.status;
    //  ONLY UPDATE FIELDS (NO NEW DOC)
    task.status = "Accepted";
    task.acceptedAt = new Date();

    task.assignmentHistory.push({
      assignedTo: agentId,
      assignedBy: task.assignedBy,
      previousStatus,
      newStatus: "Accepted",
    });

    task.taskEvents.push({
      type: "Accepted",
      details: "Task accepted by agent",
      by: agentId,
    });

    await task.save(); // SAFE

    return res.status(200).json({
      success: true,
      message: "Task accepted successfully",
      data: {
        taskId: task._id,
        status: task.status,
        acceptedAt: task.acceptedAt,
      },
    });
  } catch (err) {
    console.error("ACCEPT TASK ERROR:", err);
    return res.status(500).json({
      success: false,
      message: "Failed to accept task",
    });
  }
};


const rejectTask = async (req, res) => {
  try {
    const { reason } = req.body;
    const { id: taskId } = req.params;
    const agentId = req.user._id;

    const task = await Task.findOne({
      _id: taskId,
      assignedTo: agentId,
      isDeleted: false,
    });

    if (!task) {
      return res.status(404).json({
        success: false,
        message: "Task not found or not assigned to you",
      });
    }

    // SINGLE SOURCE OF TRUTH
    // if (task.status !== "Assigned") {
    //   return res.status(409).json({
    //     success: false,
    //     message: `Task cannot be rejected. Current status: ${task.status}`,
    //   });
    // }
    const ALLOWED_REJECT_STATUSES = ["Assigned", "Accepted"];

    if (!ALLOWED_REJECT_STATUSES.includes(task.status)) {
      return res.status(409).json({
        success: false,
        message: `Task cannot be rejected at this stage. Current status: ${task.status}`,
      });
    }

    /* UPDATE */
    const previousStatus = task.status;
    task.status = "Rejected";
    task.rejectedAt = new Date();
    task.rejectionReason = reason;

    task.assignmentHistory.push({
      assignedTo: agentId,
      assignedBy: task.assignedBy,
      previousStatus,
      newStatus: "Rejected",
    });

    task.taskEvents.push({
      type: "Rejected",
      details: `Task rejected by agent: ${reason}`,
      by: agentId,
    });

    await task.save();
    return res.status(200).json({
      success: true,
      message: "Task rejected successfully",
      data: {
        taskId: task._id,
        status: task.status,
        rejectedAt: task.rejectedAt,
      },
    });
  } catch (err) {
    console.error("REJECT TASK ERROR:", err);
    return res.status(500).json({
      success: false,
      message: "Failed to reject task",
    });
  }
};

// const startTask = async (req, res) => {
//   try {
//     const agentId = req.user._id;
//     const { id: taskId } = req.params;
//     const { lat, lng } = req.body; //  from frontend

//     const task = await Task.findOne({
//       _id: taskId,
//       assignedTo: agentId,
//       isDeleted: false,
//     });

//     if (!task) {
//       return res.status(404).json({
//         success: false,
//         message: "Task not found or not assigned to you",
//       });
//     }

//     if (task.status !== "Accepted") {
//       return res.status(409).json({
//         success: false,
//         message: `Task cannot be started. Current status: ${task.status}`,
//       });
//     }

//     //  Update task state
//     task.status = "In Progress";
//     task.workStartedAt = new Date();

//     if (lat && lng) {
//       task.workStartLocation = { lat, lng };
//     }

//     task.taskEvents.push({
//       type: "In Progress",
//       details: "Work started by agent",
//       by: agentId,
//     });

//     await task.save();

//     return res.json({
//       success: true,
//       message: "Task started successfully",
//       data: {
//         taskId: task._id,
//         status: task.status,
//         startedAt: task.workStartedAt,
//       },
//     });
//   } catch (err) {
//     console.error("START TASK ERROR:", err);
//     return res.status(500).json({
//       success: false,
//       message: "Failed to start task",
//     });
//   }
// };
const startTask = async (req, res) => {
  try {
    const agentId = req.user._id;
    const { id: taskId } = req.params;
    const { lat, lng } = req.body;

    const task = await Task.findOne({
      _id: taskId,
      assignedTo: agentId,
      isDeleted: false,
    });

    if (!task) {
      return res.status(404).json({
        success: false,
        message: "Task not found or not assigned to you",
      });
    }

    if (task.status !== "Accepted") {
      return res.status(409).json({
        success: false,
        message: `Task cannot be started. Current status: ${task.status}`,
      });
    }

    const previousStatus = task.status;

    // UPDATE
    task.status = "In Progress";
    task.workStartedAt = new Date();
    // workStartedAt

    if (lat && lng) {
      task.workStartLocation = { lat, lng };
    }

    //  ALWAYS WRITE HISTORY
    task.assignmentHistory.push({
      assignedTo: agentId,
      assignedBy: task.assignedBy,
      previousStatus,
      newStatus: "In Progress",
    });

    task.taskEvents.push({
      type: "In Progress",
      details: "Work started by agent",
      by: agentId,
    });

    await task.save();

    return res.status(200).json({
      success: true,
      message: "Task started successfully",
      data: {
        taskId: task._id,
        status: task.status,
        startedAt: task.workStartedAt,
      },
    });
  } catch (err) {
    console.error("START TASK ERROR:", err.message, err);
    return res.status(500).json({
      success: false,
      message: "Failed to start task",
    });
  }
};




// const completeTask = async (req, res) => {
//   try {
//     const agentId = req.user._id;
//     const { id: taskId } = req.params;
//     const { lat, lng, description } = req.body;

//     const task = await Task.findOne({
//       _id: taskId,
//       assignedTo: agentId,
//       isDeleted: false,
//     });

//     if (!task) {
//       return res.status(404).json({
//         success: false,
//         message: "Task not found",
//       });
//     }

//     if (task.status !== "In Progress") {
//       return res.status(400).json({
//         success: false,
//         message: `Task cannot be completed. Current status: ${task.status}`,
//       });
//     }

//     task.status = "Completed";
//     task.workCompletedAt = new Date();
//     task.completionRemarks = description || null;


//     if (lat && lng) {
//       task.workEndLocation = { lat, lng };
//     }

//     if (req.files && req.files.length > 5) {
//       return res.status(400).json({
//         success: false,
//         message: "Maximum 5 images are allowed per task",
//       });
//     }
//     const completionImages =
//       req.files && req.files.length > 0
//         ? req.files.map((file) => `/uploads/images/${file.filename}`)
//         : [];

//     // ================= SAVE IMAGES =================
//     if (completionImages.length) {
//       task.completionImages.push(...completionImages);
//     }

//     task.taskEvents.push({
//       type: "Completed",
//       details: "Task completed by agent",
//       by: agentId,
//     });

//     await task.save();

//     return res.status(200).json({
//       success: true,
//       message: "Task completed successfully",
//       data: {
//         taskId: task._id,
//         status: task.status,
//         completedAt: task.workCompletedAt,
//         imagesCount: task.completionImages.length,
//       },
//     });
//   } catch (err) {
//     console.error("COMPLETE TASK ERROR:", err);
//     return res.status(500).json({
//       success: false,
//       message: "Failed to complete task",
//     });
//   }
// };
const completeTask = async (req, res) => {
  try {
    const agentId = req.user._id;
    const { id: taskId } = req.params;
    const { lat, lng, description } = req.body;

    const task = await Task.findOne({
      _id: taskId,
      assignedTo: agentId,
      isDeleted: false,
    });

    if (!task) {
      return res.status(404).json({
        success: false,
        message: "Task not found",
      });
    }

    //  status validation
    if (task.status !== "In Progress") {
      return res.status(409).json({
        success: false,
        message: `Task cannot be completed. Current status: ${task.status}`,
      });
    }

    const previousStatus = task.status;

    // UPDATE STATUS
    task.status = "Completed";
    task.workCompletedAt = new Date();
    task.completionRemarks = description || null;

    if (lat && lng) {
      task.workEndLocation = { lat, lng };
    }

    if (req.files && req.files.length > 5) {
      return res.status(400).json({
        success: false,
        message: "Maximum 5 images are allowed per task",
      });
    }

    const completionImages =
      req.files && req.files.length > 0
        ? req.files.map((file) => `/uploads/images/${file.filename}`)
        : [];

    if (completionImages.length) {
      task.completionImages.push(...completionImages);
    }

    //  ALWAYS WRITE HISTORY
    task.assignmentHistory.push({
      assignedTo: agentId,
      assignedBy: task.assignedBy,
      previousStatus,
      newStatus: "Completed",
    });

    //  EVENT (NOT STATUS)
    task.taskEvents.push({
      type: "Completed",
      details: "Task completed by agent",
      by: agentId,
      at: new Date(),
    });

    await task.save();

    return res.status(200).json({
      success: true,
      message: "Task completed successfully",
      data: {
        taskId: task._id,
        status: task.status,
        completedAt: task.workCompletedAt,
        imagesCount: task.completionImages.length,
      },
    });
  } catch (err) {
    console.error("COMPLETE TASK ERROR:", err.message, err);
    return res.status(500).json({
      success: false,
      message: "Failed to complete task",
    });
  }
};





const raiseIssue = async (req, res) => {
  try {
    const agentId = req.user._id;
    const { id: taskId } = req.params;
    const { reason } = req.body;

    if (!reason) {
      return res.status(400).json({
        success: false,
        message: "Issue reason is required",
      });
    }

    const task = await Task.findOne({
      _id: taskId,
      assignedTo: agentId,
      isDeleted: false,
    });

    if (!task) {
      return res.status(404).json({
        success: false,
        message: "Task not found or not assigned to you",
      });
    }

    //  if (!["Accepted", "In Progress"].includes(task.status)) {
    //   return res.status(409).json({
    //     success: false,
    //     message: `Issue can be raised only after accepting the task. Current status: ${task.status}`,
    //   });
    // }

    // if (lat && lng) {
    //   task.workStartLocation = { lat, lng };
    // }
    // task.comments.push({
    //   text: reason,
    //   commentedBy: agentId,
    //   commentedAt: new Date(),
    // });

    /*SAVE EVENT*/
    task.taskEvents.push({
      type: "IssueRaised",
      details: reason,
      by: agentId,
      at: new Date(),
    });

    await task.save();

    return res.status(200).json({
      success: true,
      message: "Issue raised successfully",
      data: {
        taskId: task._id,
        status: task.status,
        raisedAt: new Date(),
      },
    });
  } catch (err) {
    console.error("RAISE ISSUE ERROR:", err);
    return res.status(500).json({
      success: false,
      message: "Failed to raise issue",
    });
  }
};

const getAgentTatAlerts = async (req, res) => {
  try {
    const agentId = req.user._id;
    const orgId = req.user.orgId;
    const now = new Date();

    const tasks = await Task.find({
      assignedTo: agentId,
      orgId,
      isDeleted: false,
      // status: { $nin: ["Completed", "Closed"] },
      dueDate: { $lt: now },
    })
      .select(
        "customer serviceName dueDate status priority"
      )
      .sort({ dueDate: 1 });

    return res.status(200).json({
      success: true,
      count: tasks.length,
      data: tasks,
    });
  } catch (err) {
    console.error("GET AGENT TAT ALERTS ERROR:", err.message, err);
    return res.status(500).json({
      success: false,
      message: "Failed to fetch TAT alerts",
    });
  }
};


// const createCustomer = async (req, res) => {
//     try {
//         const userId = req.user._id;
//         const orgId = req.user.orgId;
//         // if (!name || !state || !city) {
//         //     return errorResponse(res, "Name, State and City are required", 400);
//         // }
//         const {
//             name,
//             email,
//             customerNumber,
//             phone,
//             address,
//             // location,
//             state,
//             city,
//             primaryContactPerson,
//             notes,
//         } = req.body;

//         if (!name) {
//             return errorResponse(res, "Customer name and customer number is required", 400);
//         }

//         const existing = await Customer.findOne({
//             orgId,
//             customerNumber,
//             isDeleted: false,
//         });

//         if (existing) {
//             return errorResponse(
//                 res,
//                 "Customer already exists. Please search and reuse.",
//                 400
//             );
//         }
//         const customer = await Customer.create({
//             name,
//             email,
//             customerNumber,
//             phone,
//             address,
//             // location,
//             state,
//             city,
//             primaryContactPerson,
//             notes,
//             orgId,
//             createdBy: userId,
//             // updatedBy: userId,
//         });

//         await logUserAction({
//             userId,
//             orgId,
//             action: "CREATE_CUSTOMER",
//             model: "Customer",
//             modelId: customer._id,
//             req,
//         });

//         return res.status(201).json({
//             success: true,
//             message: "Customer created successfully",
//             data: customer,
//         });
//     } catch (err) {
//         if (err.code === 11000) {
//             return errorResponse(res, "Customer already exists", 400);
//         }
//         return errorResponse(res, "Failed to create customer", 500, err);
//     }
// };

module.exports = {
  getMobileDashboard,
  getAgentTasksMobile,
  acceptTask,
  rejectTask,
  startTask,
  completeTask,
  raiseIssue,
  getAgentTatAlerts,
  // createCustomer,

};
