const User = require("../models/userModel");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const sendEmail = require("../utils/sendEmail");
const {
  sendOTPVerification,
  sendInstantAcknowledgment,
  sendAbandonmentNudge,
} = require("../utils/mendingMindTemplates");

exports.sendOtp = async (req, res) => {
  const { email } = req.body;

  if (!email) {
    return res.status(400).json({
      success: false,
      message: "Email is required",
    });
  }

  // const otp = Math.floor(100000 + Math.random() * 900000);
  const otp = "123456";

  const otpExpiresAt = new Date(Date.now() + 5 * 60 * 1000); // 5 minutes expiry

  try {
    let user = await User.findOne({ email });

    if (!user) {
      return res.status(404).json({
        success: false,
        message: "User not found. Please register first.",
      });
    }

    // Check if user has mobile number
    if (!user.mobile) {
      return res.status(400).json({
        success: false,
        message:
          "Mobile number not found for this user. Please update your profile.",
      });
    }

    // Update OTP
    user.otp = otp;
    user.otpExpiresAt = otpExpiresAt;
    await user.save();

    // Send OTP using WhatsApp, SMS, and Email (same as registration)
    // const otpResult = await sendOTPVerification(
    //   user.mobile,
    //   user.email,
    //   user.fullname || "User",
    //   otp,
    //   user._id
    // );

    res.status(200).json({
      success: true,
      message: "OTP sent successfully via WhatsApp/SMS and Email.",
      data: {
        email: user.email,
        mobile: user.mobile,
        // messagingResult: otpResult,
        // otp, // Remove in production
      },
    });
  } catch (err) {
    console.error("Error sending OTP:", err);
    res.status(500).json({ success: false, message: err.message });
  }
};

exports.verifyOtp = async (req, res) => {
  const { email, otp } = req.body;

  if (!email || !otp) {
    return res.status(400).json({
      success: false,
      message: "Email and OTP are required",
    });
  }

  try {
    const user = await User.findOne({ email });

    if (!user || user.otp !== otp || user.otpExpiresAt < new Date()) {
      return res
        .status(400)
        .json({ success: false, message: "Invalid or expired OTP" });
    }

    user.isEmailVerified = true;
    user.otp = undefined;
    user.otpExpiresAt = undefined;
    await user.save();

    const token = jwt.sign({ id: user._id, role: user.role }, "SECRET_KEY");

    // Send instant acknowledgment using Mending Mind templates
    const resumeLink = `${
      process.env.FRONTEND_URL || "https://mendingmind.com"
    }/continue-form?token=${token}`;
    // const acknowledgmentResult = await sendInstantAcknowledgment(
    //   user.mobile,
    //   user.email,
    //   user.fullname,
    //   resumeLink,
    //   user._id
    // );

    res.status(200).json({
      success: true,
      message: "OTP verified successfully. Welcome messages sent.",
      data: {
        id: user._id,
        email: user.email,
        fullname: user.fullname,
        mobile: user.mobile,
        location: user.location,
        token,
        isEmailVerified: user.isEmailVerified,
        // messagingResult: acknowledgmentResult,
      },
    });
  } catch (err) {
    console.log("Error verifying OTP:", err);
    res.status(500).json({ success: false, message: err.message });
  }
};

const generateReferralCode = (name) => {
  const prefix = name.split(" ")[0].substring(0, 3).toUpperCase();
  const random = Math.floor(1000 + Math.random() * 9000);
  return `${prefix}${random}`;
};

exports.register = async (req, res) => {
  const { fullname, email, location, reason, mobile } = req.body;

  if (!fullname || !email || !location || !reason || !mobile) {
    return res.status(400).json({
      success: false,
      message: "All fields are required",
    });
  }

  try {
    let user = await User.findOne({ email });

    // const otp = Math.floor(100000 + Math.random() * 900000);
    const otp = "123456";

    const otpExpiresAt = new Date(Date.now() + 5 * 60 * 1000);

    if (!user) {
      const referralCode = generateReferralCode(fullname);
      user = new User({
        fullname,
        email,
        mobile,
        location,
        reason,
        isEmailVerified: false,
        otp,
        referralCode,
        otpExpiresAt,
        role: "user",
      });
    } else {
      user.otp = otp;
      user.otpExpiresAt = otpExpiresAt;
      user.fullname = fullname;
      user.location = location;
      user.reason = reason;
    }

    await user.save();

    // Send OTP using Mending Mind templates (WhatsApp, SMS, Email)
    // const otpResult = await sendOTPVerification(
    //   mobile,
    //   email,
    //   fullname,
    //   otp,
    //   user._id
    // );

    res.status(201).json({
      success: true,
      message: "Registration successful. OTP sent via WhatsApp/SMS and Email.",
      data: {
        fullname: user.fullname,
        email: user.email,
        location: user.location,
        otpExpiresAt: user.otpExpiresAt,
        isEmailVerified: user.isEmailVerified,
        role: user.role,
        // messagingResult: otpResult,
      },
    });
  } catch (err) {
    console.error("Registration error:", err);
    res.status(500).json({ success: false, message: err.message });
  }
};

exports.doctorSignup = async (req, res) => {
  try {
    // Destructure and trim fields
    let { fullname, email, mobile, password, gender } = req.body;

    // Trim input
    fullname = fullname ? fullname.trim() : "";
    email = email ? email.trim().toLowerCase() : "";
    mobile = mobile ? mobile.trim() : "";
    gender = gender ? gender.trim().toLowerCase() : "";

    // Validation
    if (!fullname || !email || !mobile || !password || !gender) {
      return res
        .status(400)
        .json({ success: false, message: "All fields are required" });
    }

    // Email regex (basic)
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return res
        .status(400)
        .json({ success: false, message: "Invalid email format" });
    }

    // Mobile number regex (10-15 digits, you can adjust for your requirements)
    const mobileRegex = /^\d{10,15}$/;
    if (!mobileRegex.test(mobile)) {
      return res
        .status(400)
        .json({ success: false, message: "Invalid mobile number" });
    }

    // Gender enum check
    const allowedGenders = ["male", "female", "other"];
    if (!allowedGenders.includes(gender)) {
      return res
        .status(400)
        .json({ success: false, message: "Invalid gender value" });
    }

    // Check if user exists by email or mobile
    let existingUser = await User.findOne({
      $or: [{ email: email }, { mobile: mobile }],
    });
    if (existingUser) {
      // Do not leak which field is duplicate
      return res.status(400).json({
        success: false,
        message: "Account with these details already exists",
      });
    }

    // Hash password
    const hashedPassword = await bcrypt.hash(password, 10);

    // Create user
    const user = new User({
      fullname,
      email,
      mobile,
      password: hashedPassword,
      role: "doctor",
      gender,
    });

    await user.save();

    res.status(201).json({
      success: true,
      message: "Doctor registered successfully",
      data: {
        id: user._id,
        fullname: user.fullname,
        email: user.email,
        role: user.role,
      },
    });
  } catch (err) {
    // Handle duplicate key error from MongoDB
    if (err.code === 11000) {
      // err.keyValue will contain the duplicate field
      return res.status(400).json({
        success: false,
        message: "Account with these details already exists",
      });
    }
    console.error("doctorSignup error:", err);
    res.status(500).json({ success: false, message: "Server Error" });
  }
};

exports.login = async (req, res) => {
  const { email, password } = req.body;

  if (!email || !password) {
    return res
      .status(400)
      .json({ success: false, message: "Email and password are required" });
  }

  try {
    const user = await User.findOne({ email });
    if (!user) {
      return res
        .status(400)
        .json({ success: false, message: "Invalid credentials" });
    }

    // Check if user has a password set
    if (!user.password) {
      return res.status(400).json({
        success: false,
        message:
          "Password not set for this account. Please use OTP login or reset your password.",
      });
    }

    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      return res
        .status(400)
        .json({ success: false, message: "Invalid credentials" });
    }

    const token = jwt.sign({ id: user._id, role: user.role }, "SECRET_KEY");
    res.json({
      success: true,
      message: "Login successful",
      data: {
        token,
        user: {
          id: user._id,
          fullname: user.fullname,
          email: user.email,
          role: user.role,
        },
      },
    });
  } catch (err) {
    console.error("Login error:", err);
    res.status(500).json({ success: false, message: "Server Error" });
  }
};

exports.gameForm = async (req, res) => {
  const {
    fullname,
    email,
    mobile,
    location,
    role = "user",
    reason,
    gender,
    countryCode,
  } = req.body;

  console.log("Form Data Received:", {
    fullname,
    email,
    mobile,
    location,
    role,
    reason,
    gender,
    countryCode,
  });

  // Validate required fields
  if (!fullname || !email || !mobile || !location) {
    return res.status(400).json({
      success: false,
      message: "fullname, email, mobile, location, and role are required",
    });
  }

  try {
    let user = await User.findOne({ email });

    if (!user) {
      user = new User({
        fullname,
        email,
        mobile,
        location,
        role,
        reason,
        gender,
        countryCode,
        isMobileVerified: false,
      });
    } else {
      // Optionally update user info
      user.fullname = fullname;
      user.mobile = mobile;
      user.location = location;
      user.role = role;
      user.reason = reason;
      user.gender = gender;
      user.countryCode = countryCode;
    }

    await user.save();

    // Generate a JWT token using email as payload
    const token = jwt.sign({ id: user._id, role: user.role }, "SECRET_KEY");

    res.status(201).json({
      success: true,
      message: "Registration successful. Token generated.",
      data: {
        fullname: user.fullname,
        email: user.email,
        mobile: user.mobile,
        location: user.location,
        role: user.role,
        reason: user.reason,
        gender: user.gender,
        countryCode: user.countryCode,
        isEmailVerified: user.isEmailVerified,
        token: token,
      },
    });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
};

// Function to send abandonment nudge
exports.sendAbandonmentNudge = async (req, res) => {
  const { userId } = req.body;

  if (!userId) {
    return res.status(400).json({
      success: false,
      message: "User ID is required",
    });
  }

  try {
    const user = await User.findById(userId);

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

    if (!user.mobile || !user.email || !user.fullname) {
      return res.status(400).json({
        success: false,
        message: "User contact information incomplete",
      });
    }

    // Generate resume link
    const token = jwt.sign({ id: user._id, role: user.role }, "SECRET_KEY");
    const resumeLink = `${
      process.env.FRONTEND_URL || "https://mendingmind.com"
    }/continue-form?token=${token}`;

    // Send abandonment nudge using Mending Mind templates
    // const nudgeResult = await sendAbandonmentNudge(
    //   user.mobile,
    //   user.email,
    //   user.fullname,
    //   resumeLink,
    //   user._id
    // );

    res.status(200).json({
      success: true,
      message: "Abandonment nudge sent successfully",
      data: {
        userId: user._id,
        // messagingResult: nudgeResult,
      },
    });
  } catch (err) {
    console.error("Error sending abandonment nudge:", err);
    res.status(500).json({
      success: false,
      message: "Failed to send abandonment nudge",
      error: err.message,
    });
  }
};

const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

exports.createMessage = async (req, res) => {
  try {
    const { phone } = req.query; // Get phone from query params
    const inputPhone = phone || "8959948853"; // Default test number without country code

    // Format phone number properly for India
    let formattedPhone;
    if (inputPhone.startsWith("+")) {
      formattedPhone = inputPhone;
    } else if (inputPhone.startsWith("91")) {
      formattedPhone = `+${inputPhone}`;
    } else if (inputPhone.length === 10) {
      // Indian mobile numbers are 10 digits, add +91
      formattedPhone = `+91${inputPhone}`;
    } else {
      formattedPhone = `+${inputPhone}`;
    }

    console.log("Testing WhatsApp with:");
    console.log("Account SID:", process.env.TWILIO_ACCOUNT_SID);
    console.log("WhatsApp Number:", process.env.TWILIO_WHATSAPP_NUMBER);
    console.log("Input phone:", inputPhone);
    console.log("Formatted phone:", formattedPhone);

    // Use OTP template for testing instead of free-form message
    const otpTemplateSid =
      process.env.WHATSAPP_OTP_TEMPLATE_SID ||
      "HX725084442fc5e98c390003de366d05d6";

    const message = await client.messages.create({
      from: process.env.TWILIO_WHATSAPP_NUMBER,
      to: `whatsapp:${formattedPhone}`,
      contentSid: otpTemplateSid,
      contentVariables: `{"1":"${Math.floor(
        100000 + Math.random() * 900000
      )}","2":"5"}`,
    });

    console.log("WhatsApp message sent successfully:", message.sid);
    res.status(200).json({
      success: true,
      message: "WhatsApp test message sent successfully",
      data: {
        sid: message.sid,
        body: message.body,
        to: message.to,
        from: message.from,
        status: message.status,
      },
    });
  } catch (error) {
    console.error("Error sending WhatsApp message:", error);
    res.status(500).json({
      success: false,
      message: "Failed to send WhatsApp message",
      error: {
        message: error.message,
        code: error.code,
        moreInfo: error.moreInfo,
        status: error.status,
      },
    });
  }
};

// Set password for users who registered via OTP
exports.setPassword = async (req, res) => {
  const { email, password, confirmPassword } = req.body;

  if (!email || !password || !confirmPassword) {
    return res.status(400).json({
      success: false,
      message: "Email, password, and confirm password are required",
    });
  }

  if (password !== confirmPassword) {
    return res.status(400).json({
      success: false,
      message: "Passwords do not match",
    });
  }

  if (password.length < 6) {
    return res.status(400).json({
      success: false,
      message: "Password must be at least 6 characters long",
    });
  }

  try {
    const user = await User.findOne({ email });
    if (!user) {
      return res.status(404).json({
        success: false,
        message: "User not found",
      });
    }

    if (!user.isEmailVerified) {
      return res.status(400).json({
        success: false,
        message: "Please verify your email first",
      });
    }

    // Hash the password
    const bcrypt = require("bcryptjs");
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(password, saltRounds);

    // Update user with password
    user.password = hashedPassword;
    await user.save();

    res.status(200).json({
      success: true,
      message:
        "Password set successfully. You can now login with email and password.",
    });
  } catch (error) {
    console.error("Set Password Error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
    });
  }
};

// OTP-based login for users without passwords
exports.otpLogin = async (req, res) => {
  const { email } = req.body;

  if (!email) {
    return res.status(400).json({
      success: false,
      message: "Email is required",
    });
  }

  try {
    const user = await User.findOne({ email });
    if (!user) {
      return res.status(404).json({
        success: false,
        message: "User not found with this email",
      });
    }

    // Generate OTP
    // const otp = Math.floor(100000 + Math.random() * 900000);
    const otp = "123456";
    const otpExpiresAt = new Date(Date.now() + 5 * 60 * 1000); // 5 minutes

    // Update user with OTP
    user.otp = otp;
    user.otpExpiresAt = otpExpiresAt;
    await user.save();

    // Send OTP using existing function
    // const { sendOTPVerification } = require("../utils/mendingMindTemplates");
    // await sendOTPVerification(
    //   user.mobile,
    //   user.email,
    //   user.fullname,
    //   otp,
    //   user._id
    // );

    res.status(200).json({
      success: true,
      message: "OTP sent successfully. Please check your email and phone.",
    });
  } catch (error) {
    console.error("OTP Login Error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
    });
  }
};

// Verify OTP for login
exports.verifyOtpLogin = async (req, res) => {
  const { email, otp } = req.body;

  if (!email || !otp) {
    return res.status(400).json({
      success: false,
      message: "Email and OTP are required",
    });
  }

  try {
    const user = await User.findOne({ email });

    if (!user || user.otp !== otp || user.otpExpiresAt < new Date()) {
      return res.status(400).json({
        success: false,
        message: "Invalid or expired OTP",
      });
    }

    // Clear OTP
    user.otp = undefined;
    user.otpExpiresAt = undefined;
    await user.save();

    // Generate token
    const jwt = require("jsonwebtoken");
    const token = jwt.sign({ id: user._id, role: user.role }, "SECRET_KEY");

    res.status(200).json({
      success: true,
      message: "Login successful",
      data: {
        token,
        user: {
          id: user._id,
          fullname: user.fullname,
          email: user.email,
          role: user.role,
        },
      },
    });
  } catch (error) {
    console.error("Verify OTP Login Error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
    });
  }
};
