import { PipelineStage, Types } from 'mongoose';
import { LeadInterestType } from '@/shared/constants/enum.constant';

const DAY_IN_MS = 1000 * 60 * 60 * 24;

export type ClosedLeadAggregateRow = {
  _id: Types.ObjectId;
  assignedToId?: Types.ObjectId;
  teamMemberName?: string;
  teamMemberAvatar?: string;
  interestType?: string;
  projectId?: Types.ObjectId;
  projectProperty?: string;
  customerName?: string;
  leadCreatedDate: Date;
  dealClosedDate: Date;
  dealValue?: number;
  closureDuration?: number;
};

export type OpenLeadAggregateRow = {
  _id: Types.ObjectId;
  assignedToId?: Types.ObjectId;
  teamMemberName?: string;
  teamMemberAvatar?: string;
  customerName?: string;
  projectId?: Types.ObjectId;
  projectProperty?: string;
  leadStage?: string;
  leadCreatedDate: Date;
  baseLastActivityDate?: Date;
};

export const buildSalesAgingEntityMatchStages = ({
  entityIds,
  isBrokerCompany,
}: {
  entityIds: Types.ObjectId[];
  isBrokerCompany: boolean;
}): PipelineStage[] =>
  entityIds.length > 0
    ? [
        {
          $match: {
            [isBrokerCompany ? 'selectedPropertyId' : 'selectedProjectId']:
              entityIds.length === 1 ? entityIds[0] : { $in: entityIds },
          },
        },
      ]
    : [];

export const buildSalesAgingOpenLeadFilter = (
  terminalStageIds: Types.ObjectId[],
): Record<string, unknown> =>
  terminalStageIds.length > 0 ? { leadStage: { $nin: terminalStageIds } } : {};

export const buildClosedSalesAgingPipeline = ({
  matchCriteria,
  wonStageIds,
  entityMatchStages,
  isBrokerCompany,
}: {
  matchCriteria: Record<string, unknown>;
  wonStageIds: Types.ObjectId[];
  entityMatchStages: PipelineStage[];
  isBrokerCompany: boolean;
}): PipelineStage[] => [
  { $match: { ...matchCriteria, leadStage: { $in: wonStageIds } } },
  {
    $lookup: {
      from: 'users',
      localField: 'assignedTo',
      foreignField: '_id',
      as: 'assignee',
    },
  },
  { $unwind: { path: '$assignee', preserveNullAndEmptyArrays: true } },
  {
    $lookup: {
      from: 'unitbookingorholds',
      let: { leadId: '$_id' },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                { $eq: ['$lead', '$$leadId'] },
                { $eq: ['$action', 'book'] },
              ],
            },
          },
        },
        { $sort: { createdAt: -1 } },
        { $limit: 1 },
        {
          $project: {
            project: 1,
            property: 1,
            unit: 1,
            bookingAmount: 1,
            createdAt: 1,
          },
        },
      ],
      as: 'latestBookingDoc',
    },
  },
  {
    $unwind: {
      path: '$latestBookingDoc',
      preserveNullAndEmptyArrays: true,
    },
  },
  {
    $addFields: {
      selectedProjectId: {
        $ifNull: ['$latestBookingDoc.project', '$project'],
      },
      selectedPropertyId: {
        $ifNull: ['$latestBookingDoc.property', '$property'],
      },
      selectedUnitId: { $ifNull: ['$latestBookingDoc.unit', '$unit'] },
      effectiveDealClosedDate: {
        $ifNull: ['$latestBookingDoc.createdAt', '$updatedAt'],
      },
    },
  },
  ...entityMatchStages,
  {
    $lookup: {
      from: 'projects',
      localField: 'selectedProjectId',
      foreignField: '_id',
      as: 'projectDoc',
    },
  },
  { $unwind: { path: '$projectDoc', preserveNullAndEmptyArrays: true } },
  {
    $lookup: {
      from: 'individualproperties',
      localField: 'selectedPropertyId',
      foreignField: '_id',
      as: 'propertyDoc',
    },
  },
  { $unwind: { path: '$propertyDoc', preserveNullAndEmptyArrays: true } },
  {
    $lookup: {
      from: 'units',
      localField: 'selectedUnitId',
      foreignField: '_id',
      as: 'unitDoc',
    },
  },
  { $unwind: { path: '$unitDoc', preserveNullAndEmptyArrays: true } },
  {
    $lookup: {
      from: 'customers',
      let: { leadId: '$_id' },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: ['$leadId', '$$leadId'],
            },
          },
        },
        { $sort: { createdAt: -1 } },
        { $limit: 1 },
        { $project: { _id: 1 } },
      ],
      as: 'customerDoc',
    },
  },
  {
    $unwind: { path: '$customerDoc', preserveNullAndEmptyArrays: true },
  },
  {
    $lookup: {
      from: 'customerpayments',
      let: { customerId: '$customerDoc._id' },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: ['$customerId', '$$customerId'],
            },
          },
        },
        { $sort: { createdAt: -1 } },
        { $limit: 1 },
        { $project: { totalAmount: 1 } },
      ],
      as: 'customerPaymentDoc',
    },
  },
  {
    $unwind: {
      path: '$customerPaymentDoc',
      preserveNullAndEmptyArrays: true,
    },
  },
  {
    $lookup: {
      from: 'contacts',
      localField: 'contact',
      foreignField: '_id',
      as: 'contactDoc',
    },
  },
  { $unwind: { path: '$contactDoc', preserveNullAndEmptyArrays: true } },
  {
    $addFields: {
      teamMemberName: {
        $trim: {
          input: {
            $concat: [
              { $ifNull: ['$assignee.firstName', ''] },
              ' ',
              { $ifNull: ['$assignee.lastName', ''] },
            ],
          },
        },
      },
      customerName: {
        $ifNull: [
          '$contactDetails.name',
          {
            $trim: {
              input: {
                $concat: [
                  { $ifNull: ['$contactDoc.firstName', ''] },
                  ' ',
                  { $ifNull: ['$contactDoc.lastName', ''] },
                ],
              },
            },
          },
        ],
      },
      projectProperty: {
        $cond: [
          isBrokerCompany,
          { $ifNull: ['$propertyDoc.title', 'N/A'] },
          {
            $ifNull: ['$projectDoc.projectName', '$propertyDoc.title'],
          },
        ],
      },
      propertyDealValue: {
        $cond: [
          {
            $in: ['$propertyDoc.listingType', ['rent', 'lease', 'preLeased']],
          },
          {
            $ifNull: [
              '$propertyDoc.monthlyRent',
              {
                $ifNull: ['$propertyDoc.totalPrice', '$propertyDoc.price'],
              },
            ],
          },
          {
            $ifNull: [
              '$propertyDoc.totalPrice',
              {
                $ifNull: ['$propertyDoc.price', '$propertyDoc.monthlyRent'],
              },
            ],
          },
        ],
      },
      leadEstimatedDealValue: {
        $switch: {
          branches: [
            {
              case: { $eq: ['$interestType', LeadInterestType.BUY] },
              then: '$budget',
            },
            {
              case: { $eq: ['$interestType', LeadInterestType.SELL] },
              then: '$askingPrice',
            },
            {
              case: { $eq: ['$interestType', LeadInterestType.RENT] },
              then: '$rentAmount',
            },
            {
              case: { $eq: ['$interestType', LeadInterestType.LEASE] },
              then: '$leaseAmount',
            },
          ],
          default: 0,
        },
      },
      dealValue: {
        $ifNull: [
          '$customerPaymentDoc.totalAmount',
          {
            $ifNull: [
              '$unitDoc.price',
              {
                $ifNull: [
                  '$propertyDealValue',
                  {
                    $ifNull: [
                      '$latestBookingDoc.bookingAmount',
                      '$leadEstimatedDealValue',
                    ],
                  },
                ],
              },
            ],
          },
        ],
      },
      closureDuration: {
        $ceil: {
          $divide: [
            { $subtract: ['$effectiveDealClosedDate', '$createdAt'] },
            DAY_IN_MS,
          ],
        },
      },
    },
  },
  {
    $project: {
      _id: 1,
      assignedToId: '$assignedTo',
      teamMemberName: 1,
      teamMemberAvatar: '$assignee.profileImage',
      interestType: 1,
      projectId: isBrokerCompany ? '$selectedPropertyId' : '$selectedProjectId',
      projectProperty: { $ifNull: ['$projectProperty', 'N/A'] },
      customerName: { $ifNull: ['$customerName', 'Unknown'] },
      dealValue: { $toDouble: { $ifNull: ['$dealValue', 0] } },
      leadCreatedDate: '$createdAt',
      dealClosedDate: '$effectiveDealClosedDate',
      closureDuration: { $max: ['$closureDuration', 0] },
    },
  },
  { $sort: { dealClosedDate: -1 } },
];

export const buildOpenSalesAgingPipeline = ({
  matchCriteria,
  terminalStageIds,
  entityMatchStages,
  isBrokerCompany,
}: {
  matchCriteria: Record<string, unknown>;
  terminalStageIds: Types.ObjectId[];
  entityMatchStages: PipelineStage[];
  isBrokerCompany: boolean;
}): PipelineStage[] => {
  const openLeadFilter = buildSalesAgingOpenLeadFilter(terminalStageIds);

  return [
    { $match: { ...matchCriteria, ...openLeadFilter } },
    {
      $lookup: {
        from: 'leadstages',
        localField: 'leadStage',
        foreignField: '_id',
        as: 'leadStageDoc',
      },
    },
    { $unwind: { path: '$leadStageDoc', preserveNullAndEmptyArrays: true } },
    ...(terminalStageIds.length === 0
      ? [
          {
            $match: {
              'leadStageDoc.stageName': {
                $not: { $regex: /lead won|lead lost|won|lost/i },
              },
            },
          },
        ]
      : []),
    {
      $lookup: {
        from: 'users',
        localField: 'assignedTo',
        foreignField: '_id',
        as: 'assignee',
      },
    },
    { $unwind: { path: '$assignee', preserveNullAndEmptyArrays: true } },
    {
      $lookup: {
        from: 'unitbookingorholds',
        let: { leadId: '$_id' },
        pipeline: [
          {
            $match: {
              $expr: {
                $and: [
                  { $eq: ['$lead', '$$leadId'] },
                  { $in: ['$action', ['book', 'hold']] },
                ],
              },
            },
          },
          {
            $addFields: {
              actionPriority: {
                $cond: [{ $eq: ['$action', 'book'] }, 0, 1],
              },
            },
          },
          { $sort: { createdAt: -1, actionPriority: 1 } },
          { $limit: 1 },
          { $project: { project: 1, property: 1, createdAt: 1 } },
        ],
        as: 'latestUnitActionDoc',
      },
    },
    {
      $unwind: {
        path: '$latestUnitActionDoc',
        preserveNullAndEmptyArrays: true,
      },
    },
    {
      $addFields: {
        selectedProjectId: {
          $ifNull: ['$latestUnitActionDoc.project', '$project'],
        },
        selectedPropertyId: {
          $ifNull: ['$latestUnitActionDoc.property', '$property'],
        },
      },
    },
    ...entityMatchStages,
    {
      $lookup: {
        from: 'projects',
        localField: 'selectedProjectId',
        foreignField: '_id',
        as: 'projectDoc',
      },
    },
    { $unwind: { path: '$projectDoc', preserveNullAndEmptyArrays: true } },
    {
      $lookup: {
        from: 'individualproperties',
        localField: 'selectedPropertyId',
        foreignField: '_id',
        as: 'propertyDoc',
      },
    },
    { $unwind: { path: '$propertyDoc', preserveNullAndEmptyArrays: true } },
    {
      $lookup: {
        from: 'contacts',
        localField: 'contact',
        foreignField: '_id',
        as: 'contactDoc',
      },
    },
    { $unwind: { path: '$contactDoc', preserveNullAndEmptyArrays: true } },
    {
      $addFields: {
        teamMemberName: {
          $trim: {
            input: {
              $concat: [
                { $ifNull: ['$assignee.firstName', ''] },
                ' ',
                { $ifNull: ['$assignee.lastName', ''] },
              ],
            },
          },
        },
        customerName: {
          $ifNull: [
            '$contactDetails.name',
            {
              $trim: {
                input: {
                  $concat: [
                    { $ifNull: ['$contactDoc.firstName', ''] },
                    ' ',
                    { $ifNull: ['$contactDoc.lastName', ''] },
                  ],
                },
              },
            },
          ],
        },
        projectProperty: {
          $cond: [
            isBrokerCompany,
            { $ifNull: ['$propertyDoc.title', 'N/A'] },
            { $ifNull: ['$projectDoc.projectName', '$propertyDoc.title'] },
          ],
        },
        leadStageName: { $ifNull: ['$leadStageDoc.stageName', 'Unknown'] },
        baseLastActivityDate: {
          $ifNull: [
            '$latestUnitActionDoc.createdAt',
            { $ifNull: ['$activityCountsUpdatedAt', '$updatedAt'] },
          ],
        },
      },
    },
    {
      $project: {
        _id: 1,
        assignedToId: '$assignedTo',
        teamMemberName: 1,
        teamMemberAvatar: '$assignee.profileImage',
        customerName: { $ifNull: ['$customerName', 'Unknown'] },
        projectId: isBrokerCompany
          ? '$selectedPropertyId'
          : '$selectedProjectId',
        projectProperty: { $ifNull: ['$projectProperty', 'N/A'] },
        leadStage: '$leadStageName',
        leadCreatedDate: '$createdAt',
        baseLastActivityDate: 1,
      },
    },
    { $sort: { leadCreatedDate: -1 } },
  ];
};
