require("dotenv").config();
const twilio = require("twilio");
const nodemailer = require("nodemailer");
const Notification = require("../models/Notification");

const client = twilio(
  process.env.TWILIO_ACCOUNT_SID,
  process.env.TWILIO_AUTH_TOKEN
);

const transporter = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: process.env.SMTP_EMAIL,
    pass: process.env.SMTP_PASSWORD,
  },
});

/**
 * 1) OTP Verification Templates
 */
const sendOTPVerification = async (phone, email, name, otp, userId = null) => {
  let status = "sent";
  let error = null;
  let whatsappSID = null;
  let smsSID = null;
  let emailMessageId = null;

  try {
    if (!phone || !email || !name || !otp) {
      throw new Error("Phone, email, name, and OTP are required");
    }

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

    // WhatsApp / SMS (same text)
    const message = `Your Mending Mind OTP is ${otp}. It's valid for 5 minutes.\nDo not share this code with anyone.`;

    console.log(`Attempting to send OTP to: ${formattedPhone}`);
    console.log(`WhatsApp Number: ${process.env.TWILIO_WHATSAPP_NUMBER}`);
    console.log(`Account SID: ${process.env.TWILIO_ACCOUNT_SID}`);

    // Send WhatsApp Message using template
    try {
      let whatsappResponse;

      const otpTemplateSid = process.env.WHATSAPP_OTP_TEMPLATE_SID;

      if (otpTemplateSid) {
        // Use approved WhatsApp template
        console.log("Using WhatsApp template:", otpTemplateSid);
        console.log("Sending to:", `whatsapp:${formattedPhone}`);
        console.log("Content variables:", JSON.stringify({ 1: otp, 2: "5" }));

        // Use the exact format from your working credentials file
        whatsappResponse = await client.messages.create({
          from: process.env.TWILIO_WHATSAPP_NUMBER,
          to: `whatsapp:${formattedPhone}`,
          contentSid: otpTemplateSid,
          contentVariables: `{"1":"${otp}","2":"5"}`,
        });
        console.log("✅ WhatsApp OTP sent via TEMPLATE successfully!");
        console.log("WhatsApp response:", {
          sid: whatsappResponse.sid,
          status: whatsappResponse.status,
          to: whatsappResponse.to,
        });
      } else {
        // Fallback to free-form text (may fail outside 24-hour window)
        console.log("No template SID found, using free-form message");
        whatsappResponse = await client.messages.create({
          from: process.env.TWILIO_WHATSAPP_NUMBER,
          to: `whatsapp:${formattedPhone}`,
          body: message,
        });
        console.log("WhatsApp OTP sent via free-form");
      }

      whatsappSID = whatsappResponse.sid;
      console.log("WhatsApp OTP SID:", whatsappSID);
    } catch (whatsappError) {
      console.log("WhatsApp failed, error:", whatsappError.message);
      console.log("WhatsApp error code:", whatsappError.code);
      console.log("WhatsApp error details:", {
        code: whatsappError.code,
        moreInfo: whatsappError.moreInfo,
        status: whatsappError.status,
      });

      // Fallback to SMS if WhatsApp fails and SMS number is configured
      if (process.env.TWILIO_PHONE_NUMBER) {
        try {
          console.log("Trying SMS fallback...");
          const smsResponse = await client.messages.create({
            from: process.env.TWILIO_PHONE_NUMBER,
            to: formattedPhone,
            body: message,
          });
          smsSID = smsResponse.sid;
          console.log("SMS OTP SID:", smsSID);
        } catch (smsError) {
          console.log("SMS also failed:", smsError.message);
          throw new Error(
            `Both WhatsApp and SMS failed. WhatsApp: ${whatsappError.message}, SMS: ${smsError.message}`
          );
        }
      } else {
        console.log("No SMS fallback configured (TWILIO_PHONE_NUMBER missing)");
        console.log("WhatsApp failed but will continue with email only");
        // Don't throw error, continue with email
      }
    }

    // Send Email
    const mailOptions = {
      from: `MendingMind ${process.env.SMTP_EMAIL}`,
      to: email,
      subject: "Your Mending Mind OTP",
      text: `Hi ${name},\n\nYour OTP is ${otp}. It's valid for 5 minutes.\nPlease don't share this code with anyone.\n\nTeam Mending Mind`,
    };

    const emailResponse = await transporter.sendMail(mailOptions);
    emailMessageId = emailResponse.messageId;
    console.log("OTP Email Sent:", emailMessageId);
  } catch (err) {
    status = "failed";
    error = err.message || "Unknown error";
    console.error("Error sending OTP:", error);
  }

  // Log notification
  try {
    await Notification.create({
      user: userId,
      type: "otp_verification",
      recipient: `${phone} / ${email}`,
      message: `OTP sent: ${otp}`,
      status,
      error,
      sentAt: new Date(),
    });
  } catch (logErr) {
    console.error("Failed to log OTP notification:", logErr.message);
  }

  return {
    success: status === "sent",
    message:
      status === "sent"
        ? "OTP sent successfully via WhatsApp/SMS and Email"
        : "Failed to send OTP",
    data: {
      whatsappSID,
      smsSID,
      emailMessageId,
      status,
      error,
    },
  };
};

/**
 * 2) Instant Acknowledgment Templates (send after OTP is verified)
 */
const sendInstantAcknowledgment = async (
  phone,
  email,
  name,
  resumeLink,
  userId = null
) => {
  let status = "sent";
  let error = null;
  let whatsappSID = null;
  let smsSID = null;
  let emailMessageId = null;

  try {
    if (!phone || !email || !name || !resumeLink) {
      throw new Error("Phone, email, name, and resume link are required");
    }

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

    // WhatsApp Message
    const whatsappMessage = `Hi ${name}, thanks for being here with Mending Mind 🌿\n\nYour verification is complete. You can continue your form anytime here → ${resumeLink}`;

    // SMS Message
    const smsMessage = `Hi ${name}, verification complete.\n\nContinue your Mending Mind form anytime: ${resumeLink}`;

    // Send WhatsApp Message using template
    try {
      let whatsappResponse;

      const acknowledgmentTemplateSid =
        process.env.WHATSAPP_INSTANT_ACKNOWLEDGEMENT_TEMPLATE_SID;

      if (acknowledgmentTemplateSid) {
        // Use WhatsApp template for instant acknowledgment
        console.log(
          "Using WhatsApp instant acknowledgment template:",
          acknowledgmentTemplateSid
        );

        whatsappResponse = await client.messages.create({
          from: process.env.TWILIO_WHATSAPP_NUMBER,
          to: `whatsapp:${formattedPhone}`,
          contentSid: acknowledgmentTemplateSid,
          contentVariables: `{"1":"${name}","2":"${resumeLink}"}`,
        });
        console.log(
          "✅ WhatsApp instant acknowledgment sent via template:",
          acknowledgmentTemplateSid
        );
      } else {
        // Fallback to free-form message
        whatsappResponse = await client.messages.create({
          from: process.env.TWILIO_WHATSAPP_NUMBER,
          to: `whatsapp:${formattedPhone}`,
          body: whatsappMessage,
        });
        console.log("✅ WhatsApp acknowledgment sent via free-form");
      }

      whatsappSID = whatsappResponse.sid;
      console.log("📱 WhatsApp Acknowledgment SID:", whatsappSID);
    } catch (whatsappError) {
      console.log("WhatsApp failed, trying SMS:", whatsappError.message);

      // Fallback to SMS if WhatsApp fails
      if (process.env.TWILIO_PHONE_NUMBER) {
        try {
          const smsResponse = await client.messages.create({
            from: process.env.TWILIO_PHONE_NUMBER,
            to: formattedPhone,
            body: smsMessage,
          });
          smsSID = smsResponse.sid;
          console.log("SMS Acknowledgment SID:", smsSID);
        } catch (smsError) {
          console.log("SMS acknowledgment also failed:", smsError.message);
        }
      } else {
        console.log("No SMS fallback configured");
      }
    }

    // Send Email
    const mailOptions = {
      from: `MendingMind ${process.env.SMTP_EMAIL}`,
      to: email,
      subject: "Welcome to Mending Mind 🌱",
      text: `Hi ${name},\n\nThank you for verifying your details with Mending Mind.\n\nYou can continue filling your form anytime using this link:\n${resumeLink}\n\nWith warmth,\nTeam Mending Mind`,
    };

    const emailResponse = await transporter.sendMail(mailOptions);
    emailMessageId = emailResponse.messageId;
    console.log("Acknowledgment Email Sent:", emailMessageId);
  } catch (err) {
    status = "failed";
    error = err.message || "Unknown error";
    console.error("Error sending acknowledgment:", error);
  }

  // Log notification
  try {
    await Notification.create({
      user: userId,
      type: "acknowledgment",
      recipient: `${phone} / ${email}`,
      message: "Verification acknowledgment sent",
      status,
      error,
      sentAt: new Date(),
    });
  } catch (logErr) {
    console.error("Failed to log acknowledgment notification:", logErr.message);
  }

  return {
    success: status === "sent",
    message:
      status === "sent"
        ? "Acknowledgment sent successfully via WhatsApp/SMS and Email"
        : "Failed to send acknowledgment",
    data: {
      whatsappSID,
      smsSID,
      emailMessageId,
      status,
      error,
    },
  };
};

/**
 * 3) Abandonment Nudge Templates (send if user leaves mid-way)
 */
const sendAbandonmentNudge = async (
  phone,
  email,
  name,
  resumeLink,
  userId = null
) => {
  let status = "sent";
  let error = null;
  let whatsappSID = null;
  let smsSID = null;
  let emailMessageId = null;

  try {
    if (!phone || !email || !name || !resumeLink) {
      throw new Error("Phone, email, name, and resume link are required");
    }

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

    // WhatsApp Message
    const whatsappMessage = `Hi ${name}, looks like you didn't finish your form 🌱\n\nPick up where you left off here → ${resumeLink}`;

    // SMS Message
    const smsMessage = `Hi ${name}, you can resume your Mending Mind form here: ${resumeLink}`;

    // Send WhatsApp Message using template
    try {
      let whatsappResponse;

      const abandonmentTemplateSid =
        process.env.WHATSAPP_ABANDONMENT_NUDGE_TEMPLATE_SID;

      if (abandonmentTemplateSid) {
        // Use WhatsApp template for abandonment nudge
        console.log(
          "Using WhatsApp abandonment nudge template:",
          abandonmentTemplateSid
        );

        whatsappResponse = await client.messages.create({
          from: process.env.TWILIO_WHATSAPP_NUMBER,
          to: `whatsapp:${formattedPhone}`,
          contentSid: abandonmentTemplateSid,
          contentVariables: `{"1":"${name}","2":"${resumeLink}"}`,
        });
        console.log(
          "✅ WhatsApp abandonment nudge sent via template:",
          abandonmentTemplateSid
        );
      } else {
        // Fallback to free-form message
        whatsappResponse = await client.messages.create({
          from: process.env.TWILIO_WHATSAPP_NUMBER,
          to: `whatsapp:${formattedPhone}`,
          body: whatsappMessage,
        });
        console.log("✅ WhatsApp abandonment nudge sent via free-form");
      }

      whatsappSID = whatsappResponse.sid;
      console.log("📱 WhatsApp Abandonment SID:", whatsappSID);
    } catch (whatsappError) {
      console.log("WhatsApp failed, trying SMS:", whatsappError.message);

      // Fallback to SMS if WhatsApp fails
      if (process.env.TWILIO_PHONE_NUMBER) {
        try {
          const smsResponse = await client.messages.create({
            from: process.env.TWILIO_PHONE_NUMBER,
            to: formattedPhone,
            body: smsMessage,
          });
          smsSID = smsResponse.sid;
          console.log("SMS Abandonment SID:", smsSID);
        } catch (smsError) {
          console.log("SMS abandonment also failed:", smsError.message);
        }
      } else {
        console.log("No SMS fallback configured");
      }
    }

    // Send Email
    const mailOptions = {
      from: `MendingMind ${process.env.SMTP_EMAIL}`,
      to: email,
      subject: "Resume your Mending Mind form",
      text: `Hi ${name},\n\nNo worries if you had to pause.\n\nYou can pick up your form right where you left off:\n${resumeLink}\n\nWe're here whenever you're ready 🌿\n\nTeam Mending Mind`,
    };

    const emailResponse = await transporter.sendMail(mailOptions);
    emailMessageId = emailResponse.messageId;
    console.log("Abandonment Email Sent:", emailMessageId);
  } catch (err) {
    status = "failed";
    error = err.message || "Unknown error";
    console.error("Error sending abandonment nudge:", error);
  }

  // Log notification
  try {
    await Notification.create({
      user: userId,
      type: "abandonment",
      recipient: `${phone} / ${email}`,
      message: "Abandonment nudge sent",
      status,
      error,
      sentAt: new Date(),
    });
  } catch (logErr) {
    console.error("Failed to log abandonment notification:", logErr.message);
  }

  return {
    success: status === "sent",
    message:
      status === "sent"
        ? "Abandonment nudge sent successfully via WhatsApp/SMS and Email"
        : "Failed to send abandonment nudge",
    data: {
      whatsappSID,
      smsSID,
      emailMessageId,
      status,
      error,
    },
  };
};

/**
 * 4) Appointment Confirmation with Google Meet Links
 */
const sendAppointmentConfirmation = async (
  phone,
  email,
  appointmentDetails,
  userId = null
) => {
  const {
    patientName,
    doctorName,
    date,
    startTime,
    endTime,
    meetLink,
    meetingCode,
    meetingType,
  } = appointmentDetails;

  let status = "sent";
  let error = null;
  let whatsappSID = null;
  let smsSID = null;

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

  console.log(`📞 Sending appointment confirmation to: ${formattedPhone}`);

  // Create appointment confirmation message
  const message = `✅ *Therapy Session Confirmed*

Hello ${patientName}! Your session with Dr. ${doctorName} is confirmed.

📅 *Date:* ${date}
⏰ *Time:* ${startTime} - ${endTime}

🎥 *Google Meet Link:*
${meetLink}

📱 *Meeting ID:* ${meetingCode || "Click link to join"}

📝 *Instructions:*
• Join 5 minutes before your session
• Test your camera and microphone
• Find a quiet, private space

Need help? Contact our support team.

*Mending Mind - Your Mental Health Partner*`;

  // Send WhatsApp Message
  try {
    let whatsappResponse;
    const isProduction = process.env.WHATSAPP_MODE === "production";

    // Check for specific meet link template first, then fallback to general appointment template
    const meetLinkTemplateSid = process.env.WHATSAPP_MEET_LINK_TEMPLATE_SID;
    const appointmentTemplateSid =
      process.env.WHATSAPP_APPOINTMENT_TEMPLATE_SID ||
      "HXb5b62575e6e4ff6129ad7c8efe1f983e";

    // Use meet link template if available and we have a meet link
    if (meetLinkTemplateSid && meetLink) {
      console.log("Using WhatsApp Meet Link template:", meetLinkTemplateSid);
      console.log("Meeting details:", {
        date,
        startTime,
        endTime,
        meetLink,
        meetingCode,
      });

      // Template variables for appointment with Google Meet link
      whatsappResponse = await client.messages.create({
        from: process.env.TWILIO_WHATSAPP_NUMBER,
        to: `whatsapp:${formattedPhone}`,
        contentSid: meetLinkTemplateSid,
        contentVariables: `{"1":"${date}","2":"${startTime}","3":"${meetLink}"}`,
      });
      console.log(
        "✅ WhatsApp appointment with Meet link sent via template:",
        meetLinkTemplateSid
      );
    } else if (appointmentTemplateSid) {
      // Use general appointment template as fallback
      console.log(
        "Using general WhatsApp appointment template:",
        appointmentTemplateSid
      );

      whatsappResponse = await client.messages.create({
        from: process.env.TWILIO_WHATSAPP_NUMBER,
        to: `whatsapp:${formattedPhone}`,
        contentSid: appointmentTemplateSid,
        contentVariables: `{"1":"${date}","2":"${startTime}"}`,
      });
      console.log(
        "✅ WhatsApp appointment sent via general template:",
        appointmentTemplateSid
      );
    } else {
      // Sandbox: Use free-form message
      whatsappResponse = await client.messages.create({
        from: process.env.TWILIO_WHATSAPP_NUMBER,
        to: `whatsapp:${formattedPhone}`,
        body: message,
      });
      console.log("✅ WhatsApp appointment sent via SANDBOX");
    }
    whatsappSID = whatsappResponse.sid;
    console.log("📱 WhatsApp Appointment SID:", whatsappSID);
  } catch (whatsappError) {
    console.error("WhatsApp appointment error:", whatsappError.message);

    // Fallback to SMS
    if (process.env.TWILIO_PHONE_NUMBER) {
      try {
        const smsResponse = await client.messages.create({
          from: process.env.TWILIO_PHONE_NUMBER,
          to: formattedPhone,
          body: message,
        });
        console.log("SMS appointment fallback sent:", smsResponse.sid);
      } catch (smsError) {
        console.error("SMS appointment fallback failed:", smsError.message);
        status = "failed";
        error = `WhatsApp: ${whatsappError.message}, SMS: ${smsError.message}`;
      }
    }
  }

  return {
    success: status === "sent",
    message:
      status === "sent"
        ? "Appointment confirmation sent successfully"
        : "Failed to send appointment confirmation",
    data: { whatsappSID, status, error },
  };
};

module.exports = {
  sendOTPVerification,
  sendInstantAcknowledgment,
  sendAbandonmentNudge,
  sendAppointmentConfirmation,
};
