import { Router } from 'express';
import prisma from '../lib/prisma.js';
import { authenticateToken, AuthRequest } from '../middleware/auth.middleware.js';
import { getIo } from '../lib/socket.js';
import { z } from 'zod';
import { validate } from '../utils/validation.js';
import { sendMessageNotification } from '../lib/fcm.js';

const router = Router();

// All routes here require authentication
router.use(authenticateToken);

// Helper: ensure user participates in conversation
async function assertUserInConversation(conversationId: string, userId: string) {
  const participant = await prisma.conversationParticipant.findFirst({
    where: { conversationId, userId },
  });

  if (!participant) {
    const error: any = new Error('You are not a participant in this conversation');
    error.status = 403;
    throw error;
  }
}

// POST /api/conversations - get or create a conversation for a property and current user
router.post('/conversations', async (req: AuthRequest, res, next) => {
  try {
    const userId = req.userId;
    const { propertyId } = req.body as { propertyId?: string };

    if (!userId) {
      return res.status(401).json({ error: 'Authentication required' });
    }

    if (!propertyId) {
      return res.status(400).json({ error: 'propertyId is required' });
    }

    const property = await prisma.property.findUnique({
      where: { id: propertyId },
      include: {
        owner: true,
        serviceEnrollments: {
          include: {
            representative: {
              include: { user: true },
            },
          },
        },
        photos: {
          where: { isPrimary: true },
          take: 1,
        },
      },
    });

    if (!property) {
      return res.status(404).json({ error: 'Property not found' });
    }

    // Determine the counterpart user (owner or representative)
    let counterpartUserId = property.ownerId;

    // If COOL_SERVICE, prefer an active enrollment representative when available
    if (property.serviceType === 'COOL_SERVICE') {
      const activeEnrollment = property.serviceEnrollments.find(
        (e) => e.status === 'ACTIVE' && e.representative?.userId,
      );
      if (activeEnrollment && activeEnrollment.representative?.userId) {
        counterpartUserId = activeEnrollment.representative.userId;
      }
    }

    if (counterpartUserId === userId) {
      return res.status(400).json({ error: 'You cannot start a conversation with yourself.' });
    }

    // Check if a conversation already exists between these two users for this property
    const existing = await prisma.conversation.findFirst({
      where: {
        propertyId,
        participants: {
          some: { userId },
        },
      },
      include: {
        participants: true,
        messages: {
          orderBy: { createdAt: 'desc' },
          take: 1,
        },
        property: {
          include: {
            photos: {
              where: { isPrimary: true },
              take: 1,
            },
          },
        },
      },
    });

    if (existing) {
      const lastMessage = existing.messages[0] ?? null;
      return res.json({
        conversation: {
          id: existing.id,
          property: {
            id: existing.property?.id,
            title: existing.property?.title,
            city: existing.property?.city,
            price: existing.property?.price,
            primaryPhotoUrl: existing.property?.photos[0]?.url ?? null,
          },
          lastMessage: lastMessage
            ? { content: lastMessage.content, createdAt: lastMessage.createdAt }
            : null,
        },
      });
    }

    const now = new Date();

    const conversation = await prisma.conversation.create({
      data: {
        property: { connect: { id: propertyId } },
        creator: { connect: { id: userId } },
        lastMessageAt: now,
        participants: {
          create: [
            { user: { connect: { id: userId } } },
            { user: { connect: { id: counterpartUserId } } },
          ],
        },
      },
      include: {
        property: {
          include: {
            photos: {
              where: { isPrimary: true },
              take: 1,
            },
          },
        },
      },
    });

    return res.status(201).json({
      conversation: {
        id: conversation.id,
        property: {
          id: conversation.property?.id,
          title: conversation.property?.title,
          city: conversation.property?.city,
          price: conversation.property?.price,
          primaryPhotoUrl: conversation.property?.photos[0]?.url ?? null,
        },
        lastMessage: null,
      },
    });
  } catch (error) {
    next(error);
  }
});

// GET /api/conversations - list current user's conversations with unread counts
router.get('/conversations', async (req: AuthRequest, res, next) => {
  console.time('conversations-fetch');
  console.log('FETCH /api/conversations hit', new Date().toISOString());
  try {
    const userId = req.userId;

    if (!userId) {
      return res.status(401).json({ error: 'Authentication required' });
    }

    const participants = await prisma.conversationParticipant.findMany({
      where: { userId },
      include: {
        conversation: {
          include: {
            property: {
              include: {
                photos: {
                  where: { isPrimary: true },
                  take: 1,
                },
              },
            },
            messages: {
              orderBy: { createdAt: 'desc' },
              take: 1,
            },
            participants: {
              include: { user: true },
            },
          },
        },
      },
      orderBy: {
        conversation: {
          lastMessageAt: 'desc',
        },
      },
    });

    const conversations = await Promise.all(
      participants
        .filter((p) => p.conversation)
        .map(async (p) => {
          const c = p.conversation!;
          const lastMessage = c.messages[0] ?? null;
          const otherParticipant = c.participants.find((cp) => cp.userId !== userId)?.user;

          const unreadCount = await prisma.message.count({
            where: {
              conversationId: c.id,
              recipientId: userId,
              readAt: null,
            },
          });

          return {
            id: c.id,
            property: c.property
              ? {
                  id: c.property.id,
                  title: c.property.title,
                  city: c.property.city,
                  price: c.property.price,
                  primaryPhotoUrl: c.property.photos[0]?.url ?? null,
                }
              : null,
            otherUser: otherParticipant
              ? {
                  id: otherParticipant.id,
                  firstName: otherParticipant.firstName,
                  lastName: otherParticipant.lastName,
                  role: otherParticipant.role,
                }
              : null,
            lastMessage: lastMessage
              ? { content: lastMessage.content, createdAt: lastMessage.createdAt }
              : null,
            unreadCount,
          };
        }),
    );

    console.timeEnd('conversations-fetch');
    return res.json({ conversations });
  } catch (error) {
    console.timeEnd('conversations-fetch');
    next(error);
  }
});

// GET /api/conversations/:id - get conversation details and messages
router.get('/conversations/:id', async (req: AuthRequest, res, next) => {
  try {
    const userId = req.userId;
    const { id } = req.params;

    if (!userId) {
      return res.status(401).json({ error: 'Authentication required' });
    }

    await assertUserInConversation(id, userId);

    const conversation = await prisma.conversation.findUnique({
      where: { id },
      include: {
        property: {
          include: {
            photos: {
              where: { isPrimary: true },
              take: 1,
            },
          },
        },
        participants: {
          include: { user: true },
        },
        messages: {
          orderBy: { createdAt: 'asc' },
        },
      },
    });

    if (!conversation) {
      return res.status(404).json({ error: 'Conversation not found' });
    }

    // Mark messages as read for this user
    const now = new Date();
    await Promise.all([
      prisma.message.updateMany({
        where: { conversationId: id, recipientId: userId, readAt: null },
        data: { readAt: now },
      }),
      prisma.conversationParticipant.updateMany({
        where: { conversationId: id, userId },
        data: { lastReadAt: now },
      }),
    ]);

    return res.json({
      conversation: {
        id: conversation.id,
        property: conversation.property
          ? {
              id: conversation.property.id,
              title: conversation.property.title,
              city: conversation.property.city,
              price: conversation.property.price,
              primaryPhotoUrl: conversation.property.photos[0]?.url ?? null,
            }
          : null,
        participants: conversation.participants.map((p) => ({
          id: p.user.id,
          firstName: p.user.firstName,
          lastName: p.user.lastName,
          role: p.user.role,
        })),
        messages: conversation.messages.map((m) => ({
          id: m.id,
          senderId: m.senderId,
          content: m.content,
          createdAt: m.createdAt,
        })),
      },
    });
  } catch (error) {
    next(error);
  }
});

// POST /api/messages - send a message in an existing conversation
const createMessageSchema = z.object({
  body: z.object({
    conversationId: z.string().min(1, 'conversationId is required'),
    content: z
      .string()
      .min(1, 'Message content is required')
      .max(2000, 'Message content is too long'),
  }),
});

router.post('/messages', validate(createMessageSchema), async (req: AuthRequest, res, next) => {
  try {
    const userId = req.userId;
    const { conversationId, content } = req.body as {
      conversationId?: string;
      content?: string;
    };

    if (!userId) {
      return res.status(401).json({ error: 'Authentication required' });
    }

    await assertUserInConversation(conversationId, userId);

    const conversation = await prisma.conversation.findUnique({
      where: { id: conversationId },
      include: {
        participants: true,
      },
    });

    if (!conversation) {
      return res.status(404).json({ error: 'Conversation not found' });
    }

    const otherParticipant = conversation.participants.find((p) => p.userId !== userId);

    if (!otherParticipant) {
      return res.status(400).json({ error: 'Conversation does not have another participant' });
    }

    const message = await prisma.message.create({
      data: {
        conversation: { connect: { id: conversationId } },
        sender: { connect: { id: userId } },
        recipient: { connect: { id: otherParticipant.userId } },
        content: content.trim(),
      },
    });

    await prisma.conversation.update({
      where: { id: conversationId },
      data: {
        lastMessageAt: message.createdAt,
      },
    });

    // Get sender info and property info for notification
    const [sender, conversationWithProperty] = await Promise.all([
      prisma.user.findUnique({
        where: { id: userId },
        select: { firstName: true, lastName: true },
      }),
      prisma.conversation.findUnique({
        where: { id: conversationId },
        include: {
          property: {
            select: { title: true },
          },
        },
      }),
    ]);

    const senderName =
      sender?.firstName && sender?.lastName
        ? `${sender.firstName} ${sender.lastName}`
        : sender?.firstName || 'Someone';

    // Emit real-time notification to recipient (and sender) via socket.io
    const io = getIo();
    if (io) {
      io.to(`user:${otherParticipant.userId}`).emit('message:new', {
        conversationId,
        message: {
          id: message.id,
          senderId: message.senderId,
          recipientId: message.recipientId,
          content: message.content,
          createdAt: message.createdAt,
        },
      });

      // Also notify sender so their UI can update without re-fetch
      io.to(`user:${userId}`).emit('message:new', {
        conversationId,
        message: {
          id: message.id,
          senderId: message.senderId,
          recipientId: message.recipientId,
          content: message.content,
          createdAt: message.createdAt,
        },
      });
    }

    // Send FCM push notification to recipient (if notifications enabled)
    const participant = await prisma.conversationParticipant.findFirst({
      where: {
        conversationId,
        userId: otherParticipant.userId,
      },
      select: {
        notificationsEnabled: true,
        mutedUntil: true,
      },
    });

    if (
      participant?.notificationsEnabled !== false &&
      (!participant?.mutedUntil || participant.mutedUntil < new Date())
    ) {
      // Send notification asynchronously (don't wait for it)
      sendMessageNotification(
        otherParticipant.userId,
        senderName,
        message.content,
        conversationId,
        conversationWithProperty?.property?.title || undefined
      ).catch((error) => {
        console.error('[MESSAGES] Failed to send FCM notification:', error);
      });
    }

    return res.status(201).json({
      message: {
        id: message.id,
        senderId: message.senderId,
        content: message.content,
        createdAt: message.createdAt,
      },
    });
  } catch (error) {
    next(error);
  }
});

export default router;