import { Router } from "express";
// import { genSalt, hash, compare } from "bcryptjs";
// import jwt from "jsonwebtoken";
import passport from "passport";
// import User from "../models/user.js";
import ImageDetection from "../models/image-detections.js";
import Verification from "../models/verification.js";
import ChatRoom from "../models/chat-room.js";
import "dotenv/config";

const router = Router();

router.get(
  "/riwayat-deteksi-pasien",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    try {
      // Get current patient ID from authenticated user
      const patientId = req.user._id;

      // Find detection history for this patient, sorted latest first
      const history = await ImageDetection.find({ uploadedBy: patientId })
        .populate("verification")
        .sort({
          updatedAt: -1,
        });

      res.json(history);
    } catch (err) {
      console.error(err);
      res.status(500).json({ error: "Error retrieving detection history" });
    }
  },
);

router.get(
  "/riwayat-pengajuan-pasien",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    try {
      // Get current patient ID from authenticated user
      const patientId = req.user._id;

      // Find detection history for this patient, sorted latest first
      const history = await Verification.find({ patientId: patientId })
        .populate("imageId")
        .populate("patientId")
        .populate("doctorId")
        .sort({
          updatedAt: -1,
        });

      res.json(history);
    } catch (err) {
      console.error(err);
      res.status(500).json({ error: "Error retrieving detection history" });
    }
  },
);

router.get(
  "/riwayat-pengajuan-dokter/:verifiedStatus",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    try {
      // Get current patient ID from authenticated user
      const doctorId = req.user._id;
      const { verifiedStatus } = req.params;

      // Find detection history for this patient, sorted latest first
      const history = await Verification.find({
        doctorId: doctorId,
        verifiedStatus: verifiedStatus,
      })
        .populate("imageId")
        .populate("patientId")
        .populate("doctorId")
        .sort({
          updatedAt: -1,
        });

      res.json(history);
    } catch (err) {
      console.error(err);
      res.status(500).json({ error: "Error retrieving detection history" });
    }
  },
);

router.get(
  "/summary-dokter",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    try {
      const doctorId = req.user.id;
      const totalPatients = (
        await Verification.distinct("patientId", { doctorId })
      ).length;
      const pendingVerifications = await Verification.countDocuments({
        verifiedStatus: "not_verified",
        doctorId,
      });
      const completedVerifications = await Verification.countDocuments({
        verifiedStatus: "verified",
        doctorId,
      });

      res.json({
        totalPatients,
        pendingVerifications,
        completedVerifications,
      });
    } catch (err) {
      console.error(err);
      res.status(500).json({ error: "Failed to fetch admin summary" });
    }
  },
);

router.get(
  "/riwayat-pengajuan",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    try {
      // Get current patient ID from authenticated user
      // const patientId = req.user._id;

      // Find detection history for this patient, sorted latest first
      const history = await Verification.find({})
        .populate("imageId")
        .populate("patientId")
        .populate("doctorId")
        .sort({
          updatedAt: -1,
        });

      res.json(history);
    } catch (err) {
      console.error(err);
      res.status(500).json({ error: "Error retrieving detection history" });
    }
  },
);

router.get(
  "/chatrooms/:userId",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    try {
      const { userId } = req.params;
      const chatRooms = await ChatRoom.find({
        $or: [{ senderId: userId }, { receiverId: userId }],
      })
        .populate("senderId", "fullname profilePictureUrl")
        .populate("receiverId", "fullname profilePictureUrl")
        .sort({ updatedAt: -1 });

      res.json(chatRooms);
    } catch (err) {
      console.error("Error fetching chat rooms", err);
      res.status(500).send("Server error");
    }
  },
);

export default router;
