import jwt from "jsonwebtoken";
import appointmentModel from "../models/appointmentModel.js";
import doctorModel from "../models/doctorModel.js";
import bcrypt from "bcrypt";
import validator from "validator";
import { v2 as cloudinary } from "cloudinary";
import userModel from "../models/userModel.js";

// ✅ API for admin login
const loginAdmin = async (req, res) => {
    try {
        console.log("ADMIN LOGIN REQUEST RECEIVED");
        console.log("ENV:", process.env.ADMIN_EMAIL, process.env.ADMIN_PASSWORD, process.env.JWT_SECRET);
        console.log("BODY:", req.body);

        const { email, password } = req.body;

        // Check ENV variables
        if (!process.env.ADMIN_EMAIL || !process.env.ADMIN_PASSWORD || !process.env.JWT_SECRET) {
            return res.json({ success: false, message: "Server configuration missing" });
        }

        // Match admin login
        if (email === process.env.ADMIN_EMAIL && password === process.env.ADMIN_PASSWORD) {
            const token = jwt.sign({ email }, process.env.JWT_SECRET, { expiresIn: "7d" });
            return res.json({ success: true, token });
        }

        return res.json({ success: false, message: "Invalid admin credentials" });

    } catch (error) {
        console.log("🔥 ADMIN LOGIN ERROR FULL LOG ↓↓↓");
        console.error(error);
        return res.status(500).json({ success: false, message: "SERVER CRASHED", error: error.message });
    }
};

// ✅ Get all appointments
const appointmentsAdmin = async (req, res) => {
    try {
        const appointments = await appointmentModel.find({});
        res.json({ success: true, appointments });
    } catch (error) {
        console.log("🔥 APPOINTMENTS ERROR ↓↓↓");
        console.error(error);
        res.json({ success: false, message: error.message });
    }
};

// ✅ Cancel appointment
const appointmentCancel = async (req, res) => {
    try {
        const { appointmentId } = req.body;
        await appointmentModel.findByIdAndUpdate(appointmentId, { cancelled: true });
        res.json({ success: true, message: 'Appointment Cancelled' });
    } catch (error) {
        console.log("🔥 CANCEL ERROR ↓↓↓");
        console.error(error);
        res.json({ success: false, message: error.message });
    }
};

// ✅ Add Doctor
const addDoctor = async (req, res) => {
    try {
        const { name, email, password, speciality, degree, experience, about, fees, address } = req.body;
        const imageFile = req.file;

        if (!name || !email || !password || !speciality || !degree || !experience || !about || !fees || !address) {
            return res.json({ success: false, message: "Missing Details" });
        }

        if (!validator.isEmail(email)) {
            return res.json({ success: false, message: "Please enter a valid email" });
        }

        if (password.length < 8) return res.json({ success: false, message: "Please enter a strong password" });

        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(password, salt);

        const imageUpload = await cloudinary.uploader.upload(imageFile.path, { resource_type: "image" });
        const imageUrl = imageUpload.secure_url;

        const doctorData = {
            name,
            email,
            image: imageUrl,
            password: hashedPassword,
            speciality,
            degree,
            experience,
            about,
            fees,
            address: JSON.parse(address),
            date: Date.now()
        };

        const newDoctor = new doctorModel(doctorData);
        await newDoctor.save();

        res.json({ success: true, message: 'Doctor Added' });
    } catch (error) {
        console.log("🔥 ADD DOCTOR ERROR ↓↓↓");
        console.error(error);
        res.json({ success: false, message: error.message });
    }
};

// ✅ All doctors
const allDoctors = async (req, res) => {
    try {
        const doctors = await doctorModel.find({}).select('-password');
        res.json({ success: true, doctors });
    } catch (error) {
        console.log("🔥 ALL DOCTORS ERROR ↓↓↓");
        console.error(error);
        res.json({ success: false, message: error.message });
    }
};

// ✅ Dashboard data
const adminDashboard = async (req, res) => {
    try {
        const doctors = await doctorModel.find({});
        const users = await userModel.find({});
        const appointments = await appointmentModel.find({});

        const dashData = {
            doctors: doctors.length,
            appointments: appointments.length,
            patients: users.length,
            latestAppointments: appointments.reverse()
        };

        res.json({ success: true, dashData });
    } catch (error) {
        console.log("🔥 DASHBOARD ERROR ↓↓↓");
        console.error(error);
        res.json({ success: false, message: error.message });
    }
};

export {
    loginAdmin,
    appointmentsAdmin,
    appointmentCancel,
    addDoctor,
    allDoctors,
    adminDashboard
};
