import nodemailer from 'nodemailer';
import SMTPTransport from 'nodemailer/lib/smtp-transport';
import { RESET_PASSWORD_EMAIL_TEMPLATE, generateEmailTemplate, COMPARISON_EMAIL_TEMPLATE, Eligibility_EMAIL_TEMPLATE  } from "../lib/templates/emailTemplates";
import { ADMISSION_REQUEST_TEMPLATE } from "../lib/templates/admissionRequestTemplate";

export interface EmailOptions {
    email: string;
    verifyCode: string;
}
export interface GenericEmailOption {
    email: string;
}
export interface QueryOption{
    first_name: string;
    last_name: string;
    email: string;
    website: string;
    subject: string;
    message: string;
}
export interface SubscribeOption{
    username: string;
    randomPassword: string;
    email: string;
}
export interface EmailResponse {
    success: boolean;
    message: string;
}

export interface AdmissionRequestOption {
  to: string;
  itemType: string;
  universityName: string;
  itemName: string;
  itemLocation: string;
  userInfo: { name: string; phone: string; email: string };
  isFallback?: boolean;
  originalUniversityName?: string;
  fallbackReason?: string;
}

export interface NodemailerResponse {
    accepted: string[];  // Recipients the email was sent to
    rejected: string[];  // Recipients the email was not sent to
    response: string;    // SMTP server response
    envelope: {
        from: string;
        to: string[];
    };
    messageId: string;   // Unique ID of the sent message
}

interface CustomError extends Error {
    code?: string;
    response?: string;
    command?: string;
}

export enum FormType {
  CONTACT_US = 'contact_us',
  FREE_CONSULTATION = 'free_consultation',
  DISCOUNT_OFFER = 'discount_offer',
  APPLY_ONLINE = 'apply_online',
  JOB_OPPORTUNITIES = 'job_opportunities',
  COMPLAINTS = 'complaints',
  MINHAJ_UNIVERSITY = 'minhaj_university',
  REGISTER_FORM = 'register_form'
}

const FORM_EMAIL_CONTENT: Record<FormType, { subject: string; title: string; message: string; headerColor: string }> = {
  [FormType.CONTACT_US]: {
    subject: "Thank You for Contacting Universities Page",
    title: "Contact Request Received",
    headerColor: "#3498db",
    message: `
      <p>Thank you for reaching out to Universities Page. We have received your contact form submission and appreciate you taking the time to get in touch with us.</p>
      <p>Our team is currently reviewing your message and a dedicated representative will respond to your inquiry within 24-48 hours. We strive to address all questions and concerns promptly.</p>
      <p>If your matter is urgent, please don't hesitate to call our support line at +1 (555) 123-4567.</p>
    `
  },
  
  [FormType.FREE_CONSULTATION]: {
    subject: "Your Free Consultation Request - Universities Page",
    title: "Consultation Request Confirmed",
    headerColor: "#9b59b6",
    message: `
      <p>Thank you for requesting a free consultation with Universities Page! We're excited to help you with your educational journey.</p>
      <p>Our education experts are preparing for your consultation session and will contact you within the next business day to schedule a convenient time for your personalized session.</p>
      <p>During the consultation, we'll discuss your goals, preferred programs, and answer any questions you may have about universities and admissions.</p>
    `
  },
  
  [FormType.DISCOUNT_OFFER]: {
    subject: "Discount Offer Application Received - Universities Page",
    title: "Discount Request Submitted",
    headerColor: "#e74c3c",
    message: `
      <p>Thank you for your interest in our special discount offers! We have received your discount application.</p>
      <p>Our admissions team will review your request and get back to you within 2 business days with the best possible offer for your chosen program.</p>
      <p>We're committed to making quality education accessible and will do our best to accommodate your needs.</p>
    `
  },
  
  [FormType.APPLY_ONLINE]: {
    subject: "Application Submitted Successfully - Universities Page",
    title: "Application Received",
    headerColor: "#2ecc71",
    message: `
      <p>Congratulations! Your application has been submitted successfully to Universities Page.</p>
      <p>Our admissions committee has received your application and will begin the review process. You can expect to hear back from us within 5-7 business days regarding the next steps.</p>
      <p>We wish you the best of luck with your application and look forward to potentially welcoming you to our academic community.</p>
    `
  },
  
  [FormType.JOB_OPPORTUNITIES]: {
    subject: "Job Application Received - Universities Page",
    title: "Job Application Submitted",
    headerColor: "#f39c12",
    message: `
      <p>Thank you for applying to join the Universities Page team! We have received your job application.</p>
      <p>Our HR department will carefully review your qualifications and experience. If your profile matches our requirements, we will contact you for the next stage of the recruitment process within 1-2 weeks.</p>
      <p>We appreciate your interest in building your career with us.</p>
    `
  },
  
  [FormType.COMPLAINTS]: {
    subject: "Complaint Registered - Universities Page",
    title: "Complaint Received",
    headerColor: "#e67e22",
    message: `
      <p>We have received your complaint and want to assure you that we take your feedback very seriously.</p>
      <p>Our quality assurance team will investigate your concern thoroughly and work towards a satisfactory resolution. You can expect a response from our support team within 24-48 hours.</p>
      <p>Thank you for helping us improve our services. Your feedback is valuable to us.</p>
    `
  },
  
  [FormType.MINHAJ_UNIVERSITY]: {
    subject: "Minhaj University Inquiry Received",
    title: "Minhaj University Application",
    headerColor: "#1abc9c",
    message: `
      <p>Thank you for your interest in Minhaj University! We have received your inquiry and are pleased to assist you.</p>
      <p>Our dedicated admission counselors for Minhaj University will contact you within 24 hours to provide detailed information about programs, admission requirements, and the application process.</p>
      <p>We look forward to helping you take this important step in your educational journey.</p>
    `
  },
  
  [FormType.REGISTER_FORM]: {
    subject: "Welcome to Universities Page!",
    title: "Registration Successful",
    headerColor: "#34495e",
    message: `
      <p>Welcome to Universities Page! Your account has been created successfully.</p>
      <p>You now have access to our comprehensive database of universities, programs, and admission guidance. Feel free to explore our resources and don't hesitate to contact us if you need any assistance.</p>
      <p>Thank you for joining our community of students and educators!</p>
    `
  }
};

/*export const sendFormEmail = async (
  formType: FormType,
  options: GenericEmailOption
): Promise<NodemailerResponse> => {
  try {
    const content = FORM_EMAIL_CONTENT[formType];
    const transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST || "sandbox.smtp.mailtrap.io",
      port: parseInt(process.env.SMTP_PORT || "587"),
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASSWORD
      }
    } as SMTPTransport.Options);

    const mailOptions = {
      from: process.env.FROM_EMAIL_ADDRESS,
      to: options.email,
      subject: content.subject,
      html: generateEmailTemplate(options, content)
    };

    const mailResponse = await transporter.sendMail(mailOptions);
    return mailResponse as NodemailerResponse;

  } catch (error: unknown) {
    if (error instanceof Error) {
      const customError = error as CustomError;
      const errorMessage = customError.response
        ? `SMTP Error: ${customError.response}`
        : customError.message;
      throw new Error(errorMessage);
    } else {
      throw new Error("An unknown error occurred during email sending.");
    }
  }
};*/

export const sendFormEmail = async (
  formType: FormType,
  options: GenericEmailOption
): Promise<NodemailerResponse> => {
  try {
    const content = FORM_EMAIL_CONTENT[formType];

    const isFallback = false;
    const transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST || "sandbox.smtp.mailtrap.io",
      port: parseInt(process.env.SMTP_PORT || "587"),
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASSWORD
      }
    } as SMTPTransport.Options);

    const mailOptions = {
      from: '"UniversitiesPage" <info@universitiespage.com>',
      to: options.email,
      subject: content.subject,
      html: generateEmailTemplate(isFallback, content)
    };

    const mailResponse = await transporter.sendMail(mailOptions);
    return mailResponse as NodemailerResponse;

  } catch (error: unknown) {
    if (error instanceof Error) {
      const customError = error as CustomError;
      const errorMessage = customError.response
        ? `SMTP Error: ${customError.response}`
        : customError.message;
      throw new Error(errorMessage);
    } else {
      throw new Error("An unknown error occurred during email sending.");
    }
  }
};

export const ResetPasswordTemplate = async ({email, verifyCode}: EmailOptions): Promise<NodemailerResponse> => {

    try {

        const transporter = nodemailer.createTransport({
        host: process.env.SMTP_HOST || "sandbox.smtp.mailtrap.io",
        port: process.env.SMTP_PORT || 587,
        auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASSWORD
            }
        } as SMTPTransport.Options);
        
        const mailOptions = {
        from: '"UniversitiesPage" <info@universitiespage.com>',
        to: email, // list of receivers
        subject: "Recover your password", // Subject line
        html: RESET_PASSWORD_EMAIL_TEMPLATE(verifyCode),
        }

        const mailResponse = await transporter.sendMail(mailOptions);
        return mailResponse as NodemailerResponse;

    } catch (error: unknown) {
        // Narrow down the error type
        if (error instanceof Error) {
            const customError = error as CustomError;
            const errorMessage = customError.response
                ? `SMTP Error: ${customError.response}`
                : customError.message;
            throw new Error(errorMessage);
        } else {
            throw new Error("An unknown error occurred during email sending.");
        }
    }

}

export const AdmissionRequestTemplate = async ({
  to,
  itemType,
  universityName,
  itemName,
  itemLocation,
  userInfo,
  isFallback = false,
  originalUniversityName,
  fallbackReason
}: AdmissionRequestOption): Promise<NodemailerResponse> => {
  try {
    console.log('🔧 SMTP Configuration Check:', {
      host: process.env.SMTP_HOST,
      port: process.env.SMTP_PORT,
      user: process.env.SMTP_USER ? '***' : 'MISSING',
      from: process.env.SMTP_FROM,
      secure: process.env.SMTP_SECURE
    });

    // Validate required environment variables
    if (!process.env.SMTP_USER || !process.env.SMTP_PASSWORD) {
      throw new Error('SMTP credentials are missing. Please check your environment variables.');
    }

    const transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST || "smtp.gmail.com",
      port: parseInt(process.env.SMTP_PORT) || 465,
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASSWORD
      },
      // Add better timeout and connection settings
      connectionTimeout: 10000,
      greetingTimeout: 10000,
      socketTimeout: 10000
    } as SMTPTransport.Options);

    // Test the connection first
    try {
      console.log('🔌 Testing SMTP connection...');
      await transporter.verify();
      console.log('✅ SMTP Connection verified successfully');
    } catch (verifyError) {
      console.error('❌ SMTP Connection failed:', verifyError);
      throw new Error(`SMTP Connection failed: ${verifyError.message}`);
    }

    const subject = isFallback 
      ? `🚨 MISSING UNIVERSITY EMAIL - Admission Request: ${itemType} - ${itemName}`
      : `New Admission Request: ${itemType} - ${itemName}`;

    const mailOptions = {
      from: '"UniversitiesPage" <info@universitiespage.com>',
      to: to,
      subject: subject,
      html: ADMISSION_REQUEST_TEMPLATE({
        itemType,
        universityName,
        itemName,
        itemLocation,
        userInfo,
        isFallback,
        originalUniversityName,
        fallbackReason
      }),
      // Add headers for better deliverability
      headers: {
        'X-Priority': '1',
        'X-Mailer': 'UniversitiesPage'
      }
    };

    console.log('📤 Sending admission request email:', {
      to: mailOptions.to,
      subject: mailOptions.subject,
      from: mailOptions.from,
      itemType,
      universityName,
      isFallback
    });

    const mailResponse = await transporter.sendMail(mailOptions);
    
    console.log('✅ Email delivery status:', {
      messageId: mailResponse.messageId,
      accepted: mailResponse.accepted,
      rejected: mailResponse.rejected,
      response: mailResponse.response
    });
    
    return mailResponse as NodemailerResponse;

  } catch (error: unknown) {
    console.error('❌ AdmissionRequestTemplate Error:', error);
    
    if (error instanceof Error) {
      const customError = error as CustomError;
      let errorMessage = `Email sending failed: ${customError.message}`;
      
      if (customError.code) {
        errorMessage += ` (Code: ${customError.code})`;
      }
      if (customError.response) {
        errorMessage += ` (Response: ${customError.response})`;
      }
      if (customError.command) {
        errorMessage += ` (Command: ${customError.command})`;
      }
      
      throw new Error(errorMessage);
    } else {
      throw new Error("An unknown error occurred during email sending.");
    }
  }
};

export const ComparisonEmail = async (comparisonType, selectedItems, aiResults, userData) =>{
  try {
    const transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST || "sandbox.smtp.mailtrap.io",
      port: parseInt(process.env.SMTP_PORT || "587"),
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASSWORD
      }
    } as SMTPTransport.Options);

    const mailOptions = {
      from: '"UniversitiesPage" <info@universitiespage.com>',
      to: userData?.email,
      subject: "Comparison Email",
      html: COMPARISON_EMAIL_TEMPLATE(comparisonType, selectedItems, aiResults, userData)
    };

    const mailResponse = await transporter.sendMail(mailOptions);
    return mailResponse as NodemailerResponse;

  } catch (error: unknown) {
    if (error instanceof Error) {
      const customError = error as CustomError;
      const errorMessage = customError.response
        ? `SMTP Error: ${customError.response}`
        : customError.message;
      throw new Error(errorMessage);
    } else {
      throw new Error("An unknown error occurred during email sending.");
    }
  }
}

export const EligibilityEmail = async (eligibilityResults, userData, calculationInputs, symbol) =>{
  try {
    const transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST || "sandbox.smtp.mailtrap.io",
      port: parseInt(process.env.SMTP_PORT || "587"),
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASSWORD
      }
    } as SMTPTransport.Options);

    const mailOptions = {
      from: '"UniversitiesPage" <info@universitiespage.com>',
      to: userData?.email,
      subject: "EligibilityCalcuclator Email",
      html: Eligibility_EMAIL_TEMPLATE(eligibilityResults, userData, calculationInputs, symbol)
    };

    const mailResponse = await transporter.sendMail(mailOptions);
    return mailResponse as NodemailerResponse;

  } catch (error: unknown) {
    if (error instanceof Error) {
      const customError = error as CustomError;
      const errorMessage = customError.response
        ? `SMTP Error: ${customError.response}`
        : customError.message;
      throw new Error(errorMessage);
    } else {
      throw new Error("An unknown error occurred during email sending.");
    }
  }
}