import { Teacher } from "../models/Teacher.js";
import { Booking } from "../models/Booking.js";

// Request for to become teacher
// export const requestTeacher = async (req, res) => {
//   try {
//     const {
//       firstName,
//       lastName,
//       email,
//       phone,
//       subject,
//       experience,
//       bio,
//       userId,
//     } = req.body;
//     const teacher = new Teacher({
//       userId,
//       firstName,
//       lastName,
//       email,
//       phone,
//       subject,
//       experience,
//       bio,
//       cv: req.file ? req.file.path : null,
//       hourlyRate: 0, // default, you can update later
//     });

//     await teacher.save();
//     res.status(201).json({ success: true, teacher });
//   } catch (error) {
//     res.status(500).json({ success: false, error: error.message });
//   }
// };
// creat Teacher
export const createTeacherProfile = async (req, res) => {
  try {
    const { userId } = req.body;

    const existing = await Teacher.findOne({ userId });
    if (existing) {
      return res.status(400).json({
        success: false,
        message: "Teacher profile already exists",
      });
    }

    const { bio } = req.body;

    // If skills[] is sent, req.body.skills could be string or array
    let skills = [];
    if (req.body.skills) {
      if (Array.isArray(req.body.skills)) {
        skills = req.body.skills;
      } else {
        skills = [req.body.skills];
      }
    }

    // File path
    const introVideo = req.file ? `uploads/${req.file.filename}` : null;
    const thumbnail = req.files?.thumbnail
      ? `uploads/${req.files.thumbnail[0].filename}`
      : null;
    const teacher = await Teacher.create({
      userId,
      bio,
      skills,
      introVideo,
      thumbnail,
      availability: [],
    });

    return res.status(201).json({
      success: true,
      message: "Teacher profile created",
      data: teacher,
    });
  } catch (error) {
    console.error(error);
    return res.status(500).json({
      success: false,
      message: "Failed to create profile",
    });
  }
};
export const getTeacherByUserId = async (req, res) => {
  try {
    const { userId } = req.params; // assuming userId is in URL

    const teacher = await Teacher.findOne({ userId }).populate(
      "userId",
      "name email phone img", // only select these fields from User
    );

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

    return res.status(200).json({
      success: true,
      data: teacher,
    });
  } catch (error) {
    console.error(error);
    return res.status(500).json({
      success: false,
      message: "Failed to fetch teacher",
    });
  }
};
// Accept User

export const acceptBooking = async (req, res) => {
  try {
    const teacherId = req.user._id;
    const bookingId = req.params.id;

    const booking = await Booking.findById(bookingId);

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

    if (booking.teacherId.toString() !== teacherId.toString()) {
      return res.status(403).json({
        success: false,
        message: "Not your booking",
      });
    }

    booking.status = "accepted";

    // if zoom not created yet
    if (!booking.zoomLink) {
      booking.zoomLink = "https://zoom.us/j/generated-room-id";
    }

    await booking.save();

    return res.status(200).json({
      success: true,
      message: "Booking accepted",
      data: booking,
    });
  } catch (error) {
    return res.status(500).json({
      success: false,
      message: "Failed to accept booking",
    });
  }
};
// Set Doctor Availability
export const updateAvailability = async (req, res) => {
  try {
    const { userId, availability } = req.body;
    console.log(req.body); // fixed typo

    if (!userId || !Array.isArray(availability)) {
      return res.status(400).json({
        success: false,
        message: "userId and availability array are required",
      });
    }

    const validDays = [
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday",
      "Sunday",
    ];

    // Format availability and include timezone
    const formattedAvailability = availability.map((day) => ({
      day: day.day,
      slots: Array.isArray(day.slots)
        ? day.slots.map((s) => ({
            start: s.start, // already in 24-hour format from frontend
            end: s.end,
          }))
        : [],
      isActive: Boolean(day.isActive),
      timezone: day.timezone || "-05:00", // default fallback
    }));

    // Ensure all 7 days exist
    const finalAvailability = validDays.map((day) => {
      const existing = formattedAvailability.find((s) => s.day === day);
      return (
        existing || { day, slots: [], isActive: false, timezone: "-05:00" }
      );
    });

    const teacher = await Teacher.findOneAndUpdate(
      { userId },
      { availability: finalAvailability },
      { new: true, runValidators: true, upsert: true },
    );

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

    return res.status(200).json({
      success: true,
      message: "Availability updated successfully",
      data: teacher.availability,
    });
  } catch (error) {
    console.error("Update availability error:", error);

    if (error.name === "ValidationError") {
      return res.status(400).json({
        success: false,
        message: "Invalid availability data",
        details: error.message,
      });
    }

    res.status(500).json({
      success: false,
      message: "Server error while updating availability",
    });
  }
};
export const getAllTeachers = async (req, res) => {
  try {
    const { name, skills, minRate, maxRate } = req.query;

    const teacherFilter = {};

    if (minRate || maxRate) {
      teacherFilter.hourlyRate = {};
      if (minRate) teacherFilter.hourlyRate.$gte = Number(minRate);
      if (maxRate) teacherFilter.hourlyRate.$lte = Number(maxRate);
    }

    if (skills) {
      teacherFilter.skills = { $in: skills.split(",") };
    }

    let teachers = await Teacher.find(teacherFilter).populate({
      path: "userId",
      select: "name email phone role image",
    });

    if (name) {
      teachers = teachers.filter((t) =>
        t.userId?.name?.toLowerCase().includes(name.toLowerCase()),
      );
    }

    return res.status(200).json({
      success: true,
      count: teachers.length,
      data: teachers,
    });
  } catch (error) {
    console.error(error);
    return res.status(500).json({
      success: false,
      message: "Failed to fetch teachers",
    });
  }
};
export const getTeacherById = async (req, res) => {
  try {
    const teacher = await Teacher.findById(req.params.id).populate({
      path: "userId",
      select: "name email phone",
    });

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

    return res.status(200).json({
      success: true,
      data: teacher,
    });
  } catch (error) {
    return res.status(500).json({
      success: false,
      message: "Error fetching teacher",
    });
  }
};
// ======================= Update Teacher Profile =======================
export const updateTeacherProfile = async (req, res) => {
  try {
    const { id } = req.params;
    const { bio } = req.body;

    // skills parse
    let skills = [];

    if (req.body["skills[]"]) {
      skills = Array.isArray(req.body["skills[]"])
        ? req.body["skills[]"]
        : [req.body["skills[]"]];
    } else if (req.body.skills) {
      skills = Array.isArray(req.body.skills)
        ? req.body.skills
        : [req.body.skills];
    }

    const updateData = {
      bio,
      skills,
    };
    console.log(req.files);
    // ✅ intro video
    if (req.files?.introVideo?.[0]) {
      updateData.introVideo = "uploads/" + req.files.introVideo[0].filename;
    }

    // ✅ thumbnail
    if (req.files?.thumbnail?.[0]) {
      updateData.thumbnail = "uploads/" + req.files.thumbnail[0].filename;
    }

    const teacher = await Teacher.findByIdAndUpdate(id, updateData, {
      new: true,
    });

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

    console.log("✅ Teacher profile updated:", teacher._id);

    res.status(200).json({
      success: true,
      data: teacher,
    });
  } catch (err) {
    console.error("❌ Update teacher error:", err.message);
    res.status(500).json({
      success: false,
      message: "Failed to update teacher profile",
    });
  }
};
export const deleteTeacher = async (req, res) => {
  try {
    const teacher = await Teacher.findByIdAndDelete(req.params.id);

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

    return res.status(200).json({
      success: true,
      message: "Teacher deleted successfully",
    });
  } catch (error) {
    return res.status(500).json({
      success: false,
      message: "Delete failed",
    });
  }
};
