/* eslint-disable camelcase */
const ProjectModel = require('../../../models/ProjectModel')
const RequestModel = require('../../../models/RequestModel')
const UserModel = require('../../../models/UserModel')
const jwt = require('jsonwebtoken')
const calculateRemainingTime = (milliseconds) => {
  const days = Math.floor(milliseconds / (1000 * 60 * 60 * 24))
  const hours = Math.floor((milliseconds % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))

  return `${days} روز و ${hours} ساعت`
}
const getProjects = async (req, res, next) => {
  try {
    const token = req.header('Authorization').split(' ')[1]
    if (!token) return res.status(401).send('Access Denied')
    // eslint-disable-next-line no-unused-vars
    const decodedToken = jwt.verify(token, process.env.APP_SECRET)
    const userId = decodedToken.id
    const user = await UserModel.findById(decodedToken.id)
    const { status_filter, page = 1, limit = 10 } = req.query // افزودن پارامترهای صفحه‌بندی به درخواست
    // ساخت فیلتر برای استفاده در جستجوی MongoDB
    let filter = {} // افزودن شرط برای payment_status
    if (user.user_type === 'user') {
      if (status_filter) {
        if (status_filter === 'دریافتی') {
          filter = { created_for_user: userId, status: 'accepted' }
        } else if (status_filter === 'ارسال شده') {
          filter = { requested_users: userId, status: 'accepted' }
        } else if (status_filter === 'در دست اقدام') {
          filter = { selected_user: userId, status: 'ongoing' }
        } else if (status_filter === 'اتمام پروژه') {
          filter = { selected_user: userId, status: 'done' }
        } else if (status_filter === 'کنسل شده') {
          filter = { selected_user: userId, status: 'cancled' }
        } else {
          filter = {
            $or: [
              { selected_user: userId },
              { requested_users: userId },
              { created_for_user: userId }
            ]
          }
        }
      } else {
        filter = {
          $or: [
            { selected_user: userId },
            { requested_users: userId },
            { created_for_user: userId }
          ]
        }
      }
    } else {
      if (status_filter) {
        if (status_filter === 'منتشر شده') {
          filter = { creator_id: userId, status: 'accepted' }
        } else if (status_filter === 'در دست اقدام') {
          filter = { creator_id: userId, status: 'ongoing' }
        } else if (status_filter === 'اتمام پروژه') {
          filter = { creator_id: userId, status: 'done' }
        } else if (status_filter === 'کنسل شده') {
          filter = { creator_id: userId, status: 'cancled' }
        } else if (status_filter === 'در دست بررسی') {
          filter = { creator_id: userId, status: { $in: ['paid', 'rejected'] } }
        } else if (status_filter === 'پرداخت نشده') {
          filter = { creator_id: userId, status: 'pre_payment' }
        } else {
          filter = { creator_id: userId }
        }
      } else {
        filter = { creator_id: userId }
      }
    }
    // paid
    // دریافت لیست پروژه‌ها با استفاده از فیلتر

    // استفاده از مدل پیجینیت شده برای دریافت نتایج صفحه‌بندی شده
    const options = {
      page: parseInt(page), // تبدیل صفحه به عدد صحیح
      limit: parseInt(limit), // تبدیل محدودیت به عدد صحیح
      sort: { createdAt: -1 }
    }
    const projects = await ProjectModel.paginate(filter, options)
    const projectsWithUserInfo = await Promise.all(projects?.docs.map(async project => {
      const creator = await UserModel.findById(project.creator_id).select('first_name last_name user_name user_type is_verified profile_image gender province city rate')
      const projectWithUserInfo = {
        ...project._doc,
        creator,
        status_filter
      }
      const currentTime = new Date()
      const projectCreatedAt = new Date(project.createdAt)
      const timeDiff = project.offer_time * 24 * 60 * 60 * 1000 - (currentTime - projectCreatedAt)
      const remainingTime = calculateRemainingTime(timeDiff)
      projectWithUserInfo.remainingTime = remainingTime
      return projectWithUserInfo
    }))
    res.status(200).json({
      projects: projectsWithUserInfo,
      totalPages: projects.totalPages, // ارسال تعداد کل صفحات
      totalItems: projects.totalDocs // ارسال تعداد کل آیتم‌ها
    })
  } catch (error) {
    next(error)
  }
}
const getSingleProject = async (req, res, next) => {
  try {
    const token = req.header('Authorization').split(' ')[1]
    if (!token) return res.status(401).send('Access Denied')
    const decodedToken = jwt.verify(token, process.env.APP_SECRET)
    const userId = decodedToken.id
    const projectId = req.query.projectId
    const projectRequests = await RequestModel.find({ project: projectId })
      .populate('user', 'price time user_level first_name last_name user_name is_verified user_score rate profile_image')
      .sort({ status: 1 })
      .lean()
    const modifiedRequests = projectRequests.map(request => ({
      ...request,
      time: request?.user?._id.toString() === userId ? request.time : null,
      price: request?.user?._id.toString() === userId ? request.price : null
    }))
    const project = await ProjectModel.findById(projectId)
    if (!project) {
      return res.status(404).json({ message: 'پروژه مورد نظر یافت نشد' })
    }
    // محاسبه مبلغ باقیمانده و مجموع مبلغ پرداخت شده
    // تابع محاسبه مبلغ پرداخت شده
    const getTotalPaidAmount = (installments) => {
      let totalPaidAmount = 0
      installments.forEach(installment => {
        totalPaidAmount += installment.amount
      })
      return totalPaidAmount
    }

    // تابع محاسبه مبلغ باقیمانده
    const getRemainingAmount = (project) => {
      const totalPaidAmount = getTotalPaidAmount(project.installments)
      const remainingAmount = project.final_price - totalPaidAmount
      return remainingAmount
    }

    const totalPaidAmount = getTotalPaidAmount(project.installments)
    const remainingAmount = getRemainingAmount(project)
    // اطلاعات کاربر سازنده را نیز دریافت کنید و به آبجکت پروژه اضافه کنید
    const creator = await UserModel.findById(project.creator_id).select('first_name last_name user_name user_type is_verified profile_image gender province city rate')

    const projectWithUserInfo = {
      ...project._doc,
      creator // اضافه کردن اطلاعات کاربر به آبجکت پروژه
    }
    const selectedUser = await UserModel.findById(project.selected_user).select('_id user_name first_name last_name user_type is_verified profile_image expertise sub_expertise province city rate user_level user_score')
    projectWithUserInfo.selected_user = selectedUser
    // محاسبه مدت زمان باقی‌مانده برای پروژه
    const currentTime = new Date()
    const projectCreatedAt = new Date(project.createdAt)
    const timeDiff = project.offer_time * 24 * 60 * 60 * 1000 - (currentTime - projectCreatedAt)
    const remainingTime = calculateRemainingTime(timeDiff)
    projectWithUserInfo.remainingTime = remainingTime
    let projectDetails = projectWithUserInfo
    if ((project.selected_user && project.selected_user.toString()) === userId || project.creator_id.toString() === userId) {
      projectDetails = {
        ...projectWithUserInfo,
        total_paid_amount: totalPaidAmount,
        remaining_amount: remainingAmount
      }
    } else {
      projectDetails =
        projectWithUserInfo
    }
    // }
    res.status(200).json({ project: projectDetails, projectRequests: modifiedRequests })
  } catch (error) {
    next(error)
  }
}

const getProjectRequests = async (req, res, next) => {
  try {
    const token = req.header('Authorization').split(' ')[1]
    if (!token) return res.status(401).send('Access Denied')
    const decodedToken = jwt.verify(token, process.env.APP_SECRET)
    const userId = decodedToken.id
    // بررسی اینکه آیا کاربر ایجاد کننده پروژه است یا خیر
    const projectId = req.params.projectId
    const project = await ProjectModel.findOne({ _id: projectId, creator_id: userId })
    if (!project) {
      return res.status(403).send({ message: 'Access denied: You are not the creator of this project.' })
    }

    // تابع محاسبه مبلغ پرداخت شده
    const getTotalPaidAmount = (installments) => {
      let totalPaidAmount = 0
      installments.forEach(installment => {
        totalPaidAmount += installment.amount
      })
      return totalPaidAmount
    }

    // تابع محاسبه مبلغ باقیمانده
    const getRemainingAmount = (project) => {
      const totalPaidAmount = getTotalPaidAmount(project.installments)
      const remainingAmount = project.final_price - totalPaidAmount
      return remainingAmount
    }

    // محاسبه مبلغ باقیمانده
    const remainingAmount = getRemainingAmount(project)

    // یافتن جزییات پروژه
    const creator = await UserModel.findById(project.creator_id).select('first_name last_name user_name user_type is_verified profile_image gender province city rate')
    const selectedUser = await UserModel.findById(project.selected_user).select('_id user_name first_name last_name user_type is_verified profile_image expertise sub_expertise province city rate user_level user_score')
    const totalPaidAmount = getTotalPaidAmount(project.installments)

    const projectRequests = await RequestModel.find({ project: projectId }).populate('user', 'price time user_level first_name last_name user_name is_verified user_score rate profile_image').sort({ status: 1 })
    const projectinfo = await ProjectModel.findById(projectId) // جزییات درخواست‌های کاربران
    projectinfo.selected_user = selectedUser
    const projectDetails = {
      ...projectinfo._doc,
      creator,
      total_paid_amount: totalPaidAmount,
      remaining_amount: remainingAmount
    }
    res.status(200).json({ projectRequests, projectDetails })
  } catch (error) {
    next(error)
  }
}
module.exports = {
  getProjects, getSingleProject, getProjectRequests
}
