import { sendEmail } from "@/lib/email/resend";
import {
  adminNewPropertyModerationTemplate,
  adminAgencyVerificationTemplate,
  adminHighValuePaymentTemplate,
  agentNewInquiryTemplate,
  agentViewingScheduledTemplate,
  agentPropertyApprovedTemplate,
  agentPropertyRejectedTemplate,
  agencyVerificationStatusTemplate,
  landlordRentReceivedTemplate,
  landlordMaintenanceAlertTemplate,
  userWelcomeTemplate,
  userInquiryConfirmationTemplate,
  userPaymentReceiptTemplate,
  agencyInvitationTemplate,
} from "@/lib/email/templates";
import { formatNaira } from "@/lib/utils";

const ADMIN_EMAIL = process.env.ADMIN_EMAIL || "superadmin@nigerialisting.com";

/**
 * 1. Dispatches Lead Inquiry Emails (to Agent + Confirmation to Customer)
 */
export async function sendLeadInquiryEmails({
  lead,
  property,
  agent,
}: {
  lead: {
    id: string;
    client_name: string;
    client_email: string;
    client_phone?: string | null;
    inquiry_type: string;
    message: string;
  };
  property: {
    title: string;
    reference_code: string;
    slug: string;
  };
  agent?: {
    email?: string | null;
    first_name?: string | null;
    last_name?: string | null;
    phone_number?: string | null;
  } | null;
}) {
  const agentEmail = agent?.email;
  const agentName = agent?.first_name ? `${agent.first_name} ${agent.last_name || ""}`.trim() : "Agent";

  // 1. Send Alert to Assigned Agent / Landlord
  if (agentEmail) {
    const html = agentNewInquiryTemplate({
      agentName,
      propertyTitle: property.title,
      referenceCode: property.reference_code,
      clientName: lead.client_name,
      clientEmail: lead.client_email,
      clientPhone: lead.client_phone,
      inquiryType: lead.inquiry_type,
      message: lead.message,
      leadId: lead.id,
    });

    sendEmail({
      to: agentEmail,
      subject: `[New Inquiry] ${lead.client_name} - ${property.title} (${property.reference_code})`,
      html,
    }).catch((err) => console.warn("[Email Service] Failed to send agent inquiry email:", err));
  }

  // 2. Send Confirmation to Client
  if (lead.client_email) {
    const confirmationHtml = userInquiryConfirmationTemplate({
      userName: lead.client_name,
      propertyTitle: property.title,
      referenceCode: property.reference_code,
      agentName,
      agentPhone: agent?.phone_number,
      agentEmail: agent?.email,
      slug: property.slug,
    });

    sendEmail({
      to: lead.client_email,
      subject: `Inquiry Received: ${property.title} (Ref: ${property.reference_code})`,
      html: confirmationHtml,
    }).catch((err) => console.warn("[Email Service] Failed to send client confirmation email:", err));
  }
}

/**
 * 2. Dispatches Viewing Appointment Notifications
 */
export async function sendViewingScheduledEmails({
  appointment,
  lead,
  property,
  agent,
}: {
  appointment: {
    scheduled_at: string;
    meeting_type: string;
    meeting_location?: string | null;
    notes?: string | null;
  };
  lead: {
    client_name: string;
    client_phone?: string | null;
    client_email?: string | null;
  };
  property: {
    title: string;
  };
  agent?: {
    email?: string | null;
    first_name?: string | null;
    last_name?: string | null;
  } | null;
}) {
  const agentEmail = agent?.email;
  const agentName = agent?.first_name ? `${agent.first_name} ${agent.last_name || ""}`.trim() : "Agent";

  const formattedDate = new Date(appointment.scheduled_at).toLocaleDateString("en-NG", {
    weekday: "short",
    year: "numeric",
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });

  if (agentEmail) {
    const html = agentViewingScheduledTemplate({
      agentName,
      propertyTitle: property.title,
      scheduledAt: formattedDate,
      clientName: lead.client_name,
      clientPhone: lead.client_phone,
      meetingType: appointment.meeting_type,
      meetingLocation: appointment.meeting_location,
      notes: appointment.notes,
    });

    sendEmail({
      to: agentEmail,
      subject: `[Inspection Booked] ${formattedDate} - ${property.title}`,
      html,
    }).catch((err) => console.warn("[Email Service] Viewing notification failed:", err));
  }
}

/**
 * 3. Dispatches Property Moderation Review Alert to Admins
 */
export async function sendPropertySubmittedForReviewEmail({
  property,
  creator,
}: {
  property: {
    id: string;
    title: string;
    reference_code: string;
    price: number;
    property_type: string;
    title_type: string;
    location: string;
  };
  creator?: {
    email?: string | null;
    first_name?: string | null;
    last_name?: string | null;
  } | null;
}) {
  const html = adminNewPropertyModerationTemplate({
    propertyTitle: property.title,
    referenceCode: property.reference_code,
    price: property.price,
    propertyType: property.property_type,
    titleType: property.title_type,
    creatorName: creator?.first_name ? `${creator.first_name} ${creator.last_name || ""}`.trim() : "Platform User",
    creatorEmail: creator?.email || "unknown@user",
    location: property.location,
    propertyId: property.id,
  });

  sendEmail({
    to: ADMIN_EMAIL,
    subject: `[Moderation Queue] ${property.reference_code}: ${property.title} - ${formatNaira(property.price)}`,
    html,
  }).catch((err) => console.warn("[Email Service] Admin moderation alert failed:", err));
}

/**
 * 4. Dispatches Property Approval / Rejection Emails to Agent
 */
export async function sendPropertyModerationResult({
  property,
  creator,
  action,
  notes,
}: {
  property: {
    id: string;
    title: string;
    reference_code: string;
    slug: string;
  };
  creator?: {
    email?: string | null;
    first_name?: string | null;
    last_name?: string | null;
  } | null;
  action: "APPROVED" | "REJECTED";
  notes?: string | null;
}) {
  if (!creator?.email) return;

  const agentName = creator.first_name ? `${creator.first_name} ${creator.last_name || ""}`.trim() : "Agent";

  let html: string;
  let subject: string;

  if (action === "APPROVED") {
    html = agentPropertyApprovedTemplate({
      agentName,
      propertyTitle: property.title,
      referenceCode: property.reference_code,
      slug: property.slug,
    });
    subject = `Your Listing is Live! ${property.title} (${property.reference_code})`;
  } else {
    html = agentPropertyRejectedTemplate({
      agentName,
      propertyTitle: property.title,
      referenceCode: property.reference_code,
      propertyId: property.id,
      notes,
    });
    subject = `Action Needed: Review feedback for ${property.reference_code}`;
  }

  sendEmail({
    to: creator.email,
    subject,
    html,
  }).catch((err) => console.warn("[Email Service] Moderation result email failed:", err));
}

/**
 * 5. Dispatches Agency Verification Submission and Approval Emails
 */
export async function sendAgencyVerificationEmails({
  agency,
  owner,
  type,
  notes,
}: {
  agency: {
    id: string;
    name: string;
    cac_rc_number?: string | null;
    tax_id_number?: string | null;
    phone?: string | null;
    office_address?: string | null;
  };
  owner?: {
    email?: string | null;
    first_name?: string | null;
    last_name?: string | null;
  } | null;
  type: "SUBMITTED" | "VERIFIED" | "REJECTED";
  notes?: string | null;
}) {
  const ownerName = owner?.first_name ? `${owner.first_name} ${owner.last_name || ""}`.trim() : "Agency Principal";

  if (type === "SUBMITTED") {
    // Notify platform admins
    const html = adminAgencyVerificationTemplate({
      agencyName: agency.name,
      cacRcNumber: agency.cac_rc_number,
      taxIdNumber: agency.tax_id_number,
      ownerName,
      ownerEmail: owner?.email || "unknown@agency",
      phone: agency.phone,
      officeAddress: agency.office_address,
      agencyId: agency.id,
    });

    sendEmail({
      to: ADMIN_EMAIL,
      subject: `[CAC Verification] New Agency Application: ${agency.name}`,
      html,
    }).catch((err) => console.warn("[Email Service] Agency submission email failed:", err));
  } else if (owner?.email) {
    // Notify agency owner
    const html = agencyVerificationStatusTemplate({
      ownerName,
      agencyName: agency.name,
      status: type,
      notes,
    });

    sendEmail({
      to: owner.email,
      subject: `Agency Verification: ${agency.name} (${type})`,
      html,
    }).catch((err) => console.warn("[Email Service] Agency status email failed:", err));
  }
}

/**
 * 6. Dispatches Payment Receipts & Landlord Payout Alerts
 */
export async function sendPaymentReceiptEmails({
  payment,
  payer,
  landlordOrAgency,
}: {
  payment: {
    amount: number;
    reference: string;
    purpose: string;
    payment_date: string;
    property_name?: string | null;
    unit_name?: string | null;
  };
  payer?: {
    email?: string | null;
    first_name?: string | null;
    last_name?: string | null;
  } | null;
  landlordOrAgency?: {
    email?: string | null;
    name?: string | null;
  } | null;
}) {
  const payerName = payer?.first_name ? `${payer.first_name} ${payer.last_name || ""}`.trim() : "Valued Customer";

  // 1. Send receipt to payer
  if (payer?.email) {
    const receiptHtml = userPaymentReceiptTemplate({
      userName: payerName,
      amount: payment.amount,
      reference: payment.reference,
      purpose: payment.purpose,
      paymentDate: payment.payment_date,
      propertyName: payment.property_name,
    });

    sendEmail({
      to: payer.email,
      subject: `Payment Receipt: ${formatNaira(payment.amount)} (Ref: ${payment.reference})`,
      html: receiptHtml,
    }).catch((err) => console.warn("[Email Service] Payment receipt failed:", err));
  }

  // 2. Send settlement alert to Landlord / Agency
  if (landlordOrAgency?.email) {
    const landlordHtml = landlordRentReceivedTemplate({
      landlordName: landlordOrAgency.name || "Landlord",
      propertyName: payment.property_name || "Property",
      unit: payment.unit_name || "Main House",
      tenantName: payerName,
      amount: payment.amount,
      reference: payment.reference,
      paymentDate: payment.payment_date,
    });

    sendEmail({
      to: landlordOrAgency.email,
      subject: `[Payment Received] ${formatNaira(payment.amount)} from ${payerName}`,
      html: landlordHtml,
    }).catch((err) => console.warn("[Email Service] Landlord payout email failed:", err));
  }

  // 3. High-Value Alert to Admin
  if (payment.amount >= 5000000) {
    const adminHtml = adminHighValuePaymentTemplate({
      amount: payment.amount,
      reference: payment.reference,
      purpose: payment.purpose,
      payerName,
      payerEmail: payer?.email || "unknown@payer",
    });

    sendEmail({
      to: ADMIN_EMAIL,
      subject: `[High-Value Payment] ${formatNaira(payment.amount)} Confirmed`,
      html: adminHtml,
    }).catch((err) => console.warn("[Email Service] Admin high value alert failed:", err));
  }
}

/**
 * 7. Dispatches Welcome Email on Signup
 */
export async function sendWelcomeEmail({
  email,
  firstName,
  lastName,
}: {
  email: string;
  firstName?: string | null;
  lastName?: string | null;
}) {
  const userName = firstName ? `${firstName} ${lastName || ""}`.trim() : "there";
  const html = userWelcomeTemplate({ userName });

  sendEmail({
    to: email,
    subject: `Welcome to Nigeria Listing, ${firstName || "Friend"}!`,
    html,
  }).catch((err) => console.warn("[Email Service] Welcome email failed:", err));
}

/**
 * 8. Dispatches Urgent Maintenance Notification
 */
export async function sendMaintenanceAlertEmail({
  ticket,
  landlord,
}: {
  ticket: {
    id: string;
    title: string;
    propertyName: string;
    unit: string;
    category: string;
    priority: string;
    reportedBy: string;
  };
  landlord: {
    email: string;
    name: string;
  };
}) {
  const html = landlordMaintenanceAlertTemplate({
    landlordName: landlord.name,
    propertyName: ticket.propertyName,
    unit: ticket.unit,
    title: ticket.title,
    category: ticket.category,
    priority: ticket.priority,
    reportedBy: ticket.reportedBy,
    ticketId: ticket.id,
  });

  sendEmail({
    to: landlord.email,
    subject: `[${ticket.priority}] Maintenance Request: ${ticket.title}`,
    html,
  }).catch((err) => console.warn("[Email Service] Maintenance email failed:", err));
}

/**
 * 12. Dispatches Corporate Agency Invitation Email
 */
export async function sendAgencyInvitationEmail({
  recipientEmail,
  agencyName,
  inviterName,
  roleTitle,
  inviteUrl,
}: {
  recipientEmail: string;
  agencyName: string;
  inviterName: string;
  roleTitle: string;
  inviteUrl?: string;
}) {
  const html = agencyInvitationTemplate({
    agencyName,
    inviterName,
    roleTitle,
    recipientEmail,
    inviteUrl,
  });

  return sendEmail({
    to: recipientEmail,
    subject: `Invitation: Join ${agencyName} on Nigeria Listing`,
    html,
  });
}
