import nodemailer from "nodemailer";
import { db } from "@/db";
import { adminSettings } from "@/db/schema";
import { resolveClaimAgentEmail } from "@/lib/admin-auth";

interface ClaimNotificationPayload {
  reference: string;
  firstName: string;
  lastName: string;
  middleName?: string | null;
  dateOfBirth?: string | null;
  nationality?: string | null;
  idNumber?: string | null;
  email: string;
  phone: string;
  preferredContact: string;
  socialMedia?: string | null;
  address: string;
  city: string;
  region: string;
  postalCode: string;
  country: string;
  ticketNumber: string;
  winningNumbers: string;
  prizeAmount: string;
  paymentPreference: string;
  notes?: string | null;
  signature?: string | null;
  submissionDate?: string;
}

export async function getDbSmtpConfig() {
  try {
    const rows = await db.select().from(adminSettings);
    const hostRow = rows.find((r) => r.key === "smtp_host");
    const portRow = rows.find((r) => r.key === "smtp_port");
    const userRow = rows.find((r) => r.key === "smtp_user");
    const passRow = rows.find((r) => r.key === "smtp_pass");
    const fromRow = rows.find((r) => r.key === "smtp_from");
    const secureRow = rows.find((r) => r.key === "smtp_secure");

    return {
      host: hostRow?.value?.trim() || process.env.SMTP_HOST || "",
      port: Number(portRow?.value?.trim() || process.env.SMTP_PORT || "587"),
      user: userRow?.value?.trim() || process.env.SMTP_USER || "",
      pass: passRow?.value?.trim() || process.env.SMTP_PASS || "",
      from: fromRow?.value?.trim() || process.env.SMTP_FROM || "",
      secure: secureRow?.value === "true" || process.env.SMTP_SECURE === "true",
    };
  } catch (err) {
    console.error("Error reading SMTP settings from DB:", err);
    return {
      host: process.env.SMTP_HOST || "",
      port: Number(process.env.SMTP_PORT || "587"),
      user: process.env.SMTP_USER || "",
      pass: process.env.SMTP_PASS || "",
      from: process.env.SMTP_FROM || "",
      secure: process.env.SMTP_SECURE === "true",
    };
  }
}

export async function setDbSmtpConfig(config: {
  host?: string;
  port?: number | string;
  user?: string;
  pass?: string;
  from?: string;
  secure?: boolean;
}) {
  const entries: Array<{ key: string; value: string }> = [];

  if (config.host !== undefined) entries.push({ key: "smtp_host", value: String(config.host).trim() });
  if (config.port !== undefined) entries.push({ key: "smtp_port", value: String(config.port).trim() });
  if (config.user !== undefined) entries.push({ key: "smtp_user", value: String(config.user).trim() });
  if (config.pass !== undefined && String(config.pass).trim()) entries.push({ key: "smtp_pass", value: String(config.pass).trim() });
  if (config.from !== undefined) entries.push({ key: "smtp_from", value: String(config.from).trim() });
  if (config.secure !== undefined) entries.push({ key: "smtp_secure", value: config.secure ? "true" : "false" });

  for (const item of entries) {
    await db
      .insert(adminSettings)
      .values({ key: item.key, value: item.value, updatedAt: new Date() })
      .onConflictDoUpdate({
        target: adminSettings.key,
        set: { value: item.value, updatedAt: new Date() },
      });
  }
}

export async function sendClaimEmails(payload: ClaimNotificationPayload, request?: Request) {
  const adminAgentEmail = await resolveClaimAgentEmail(request);
  const smtp = await getDbSmtpConfig();
  const subDate = payload.submissionDate || new Date().toUTCString();

  const formattedName = `${payload.firstName} ${payload.middleName ? payload.middleName + " " : ""}${payload.lastName}`;
  const payoutText = payload.paymentPreference === "lump-sum" ? "Lump-Sum Cash Payout" : "30-Year Annuity Installments";

  // Build Claimant Email HTML
  const claimantHtml = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Powerball Claims Center Confirmation</title>
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background-color: #f1f5f9; margin: 0; padding: 24px; color: #0f172a;">
  <div style="max-width: 620px; margin: 0 auto; background: #ffffff; border-radius: 14px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.08); border: 1px solid #e2e8f0;">
    <div style="background: #082046; padding: 28px 24px; text-align: center; color: #ffffff;">
      <h1 style="margin: 0; font-size: 24px; letter-spacing: -0.5px;">POWERBALL CLAIMS CENTER</h1>
      <p style="margin: 6px 0 0; font-size: 12px; color: #cbd5e1; text-transform: uppercase; letter-spacing: 1.5px;">Official Winner Claim Confirmation</p>
    </div>

    <div style="padding: 28px 24px;">
      <p style="font-size: 15px; line-height: 1.6; margin-top: 0;">Dear <strong>${formattedName}</strong>,</p>
      <p style="font-size: 14px; line-height: 1.6; color: #334155;">
        Your official claim file for the <strong>Grand Prize Jackpot (${payload.prizeAmount})</strong> has been successfully received and recorded in our secure claims registry.
      </p>

      <div style="background: #f8fafc; border: 1.5px solid #e2e8f0; border-radius: 10px; padding: 18px; margin: 20px 0; text-align: center;">
        <span style="font-size: 11px; font-weight: 800; color: #64748b; text-transform: uppercase; letter-spacing: 1px; display: block;">Official Claim Reference Number</span>
        <strong style="font-family: monospace; font-size: 24px; color: #c81e28; letter-spacing: 1.5px; display: block; margin: 6px 0;">${payload.reference}</strong>
        <span style="font-size: 12px; color: #475569;">Keep this reference code secure. You will need it to coordinate disbursement.</span>
      </div>

      <h3 style="font-size: 14px; color: #0c1e3d; border-bottom: 2px solid #f1f5f9; padding-bottom: 8px; margin-top: 24px; text-transform: uppercase; letter-spacing: 0.5px;">Summary of Submitted Claim File:</h3>
      <table style="width: 100%; border-collapse: collapse; font-size: 13px; color: #334155;">
        <tr style="border-bottom: 1px solid #f1f5f9;">
          <td style="padding: 8px 0; color: #64748b;">Ticket Serial:</td>
          <td style="padding: 8px 0; font-family: monospace; font-weight: bold; text-align: right;">${payload.ticketNumber}</td>
        </tr>
        <tr style="border-bottom: 1px solid #f1f5f9;">
          <td style="padding: 8px 0; color: #64748b;">6 Winning Numbers:</td>
          <td style="padding: 8px 0; font-weight: bold; color: #c81e28; text-align: right;">${payload.winningNumbers}</td>
        </tr>
        <tr style="border-bottom: 1px solid #f1f5f9;">
          <td style="padding: 8px 0; color: #64748b;">Prize Tier & Value:</td>
          <td style="padding: 8px 0; font-weight: bold; text-align: right;">Grand Prize Jackpot (${payload.prizeAmount})</td>
        </tr>
        <tr style="border-bottom: 1px solid #f1f5f9;">
          <td style="padding: 8px 0; color: #64748b;">Selected Payout Option:</td>
          <td style="padding: 8px 0; font-weight: bold; text-align: right;">${payoutText}</td>
        </tr>
        <tr style="border-bottom: 1px solid #f1f5f9;">
          <td style="padding: 8px 0; color: #64748b;">Address on File:</td>
          <td style="padding: 8px 0; text-align: right;">${payload.address}, ${payload.city}, ${payload.region} ${payload.postalCode}, ${payload.country}</td>
        </tr>
        <tr style="border-bottom: 1px solid #f1f5f9;">
          <td style="padding: 8px 0; color: #64748b;">Contact Details:</td>
          <td style="padding: 8px 0; text-align: right;">${payload.email} | ${payload.phone}</td>
        </tr>
        <tr style="border-bottom: 1px solid #f1f5f9;">
          <td style="padding: 8px 0; color: #64748b;">Digital Signature:</td>
          <td style="padding: 8px 0; font-style: italic; text-align: right;">${payload.signature || formattedName}</td>
        </tr>
        <tr>
          <td style="padding: 8px 0; color: #64748b;">Submission Timestamp:</td>
          <td style="padding: 8px 0; text-align: right;">${subDate}</td>
        </tr>
      </table>

      <div style="background: #fffbeb; border: 1px solid #fde68a; border-radius: 8px; padding: 14px; margin-top: 24px; font-size: 12px; color: #92400e;">
        <strong>Next Steps:</strong> Your designated claim agent (${adminAgentEmail}) will review your submission file. You may email your claim reference code directly to <strong>${adminAgentEmail}</strong> to check ongoing status.
      </div>
    </div>

    <div style="background: #f8fafc; border-top: 1px solid #e2e8f0; padding: 16px 24px; text-align: center; font-size: 11px; color: #94a3b8;">
      Powerball Claims Center · Form PB-1040 · Automated Notification System
    </div>
  </div>
</body>
</html>
  `;

  // Build Admin / Agent Notification Email HTML
  const adminHtml = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>New Winner Claim File Received</title>
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background-color: #f1f5f9; margin: 0; padding: 24px; color: #0f172a;">
  <div style="max-width: 660px; margin: 0 auto; background: #ffffff; border-radius: 14px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.08); border: 1px solid #e2e8f0;">
    <div style="background: #c81e28; padding: 24px; text-align: center; color: #ffffff;">
      <h1 style="margin: 0; font-size: 22px;">NEW WINNER CLAIM FILE SUBMISSION</h1>
      <p style="margin: 4px 0 0; font-size: 12px; color: #fee2e2; letter-spacing: 1px;">ACTION REQUIRED · CLAIMS AGENT DOSSIER</p>
    </div>

    <div style="padding: 28px 24px;">
      <div style="background: #f0f7ff; border: 1px solid #bae6fd; border-radius: 10px; padding: 16px; margin-bottom: 22px;">
        <div style="display: flex; justify-content: space-between; margin-bottom: 6px;">
          <span style="font-size: 11px; font-weight: bold; color: #0369a1; text-transform: uppercase;">Generated Reference:</span>
          <strong style="font-family: monospace; font-size: 16px; color: #0c4a6e;">${payload.reference}</strong>
        </div>
        <div style="display: flex; justify-content: space-between;">
          <span style="font-size: 11px; font-weight: bold; color: #0369a1; text-transform: uppercase;">Ticket Serial Number:</span>
          <strong style="font-family: monospace; font-size: 15px; color: #0c4a6e;">${payload.ticketNumber}</strong>
        </div>
      </div>

      <h3 style="font-size: 14px; color: #0c1e3d; border-bottom: 2px solid #e2e8f0; padding-bottom: 6px; margin: 18px 0 10px; text-transform: uppercase;">Claimant Identification</h3>
      <table style="width: 100%; border-collapse: collapse; font-size: 13px;">
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b; width: 40%;">Full Name:</td><td style="padding: 6px 0; font-weight: bold;">${formattedName}</td></tr>
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b;">Date of Birth:</td><td style="padding: 6px 0;">${payload.dateOfBirth || "N/A"}</td></tr>
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b;">Nationality:</td><td style="padding: 6px 0;">${payload.nationality || "N/A"}</td></tr>
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b;">Govt ID / Passport:</td><td style="padding: 6px 0;">${payload.idNumber || "N/A"}</td></tr>
      </table>

      <h3 style="font-size: 14px; color: #0c1e3d; border-bottom: 2px solid #e2e8f0; padding-bottom: 6px; margin: 20px 0 10px; text-transform: uppercase;">Contact & Worldwide Address</h3>
      <table style="width: 100%; border-collapse: collapse; font-size: 13px;">
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b; width: 40%;">Email Address:</td><td style="padding: 6px 0; font-weight: bold; color: #0284c7;"><a href="mailto:${payload.email}">${payload.email}</a></td></tr>
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b;">Phone Number:</td><td style="padding: 6px 0; font-weight: bold;"><a href="tel:${payload.phone}">${payload.phone}</a></td></tr>
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b;">Preferred Contact:</td><td style="padding: 6px 0;">${payload.preferredContact}</td></tr>
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b;">Social / WhatsApp:</td><td style="padding: 6px 0;">${payload.socialMedia || "N/A"}</td></tr>
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b;">Address:</td><td style="padding: 6px 0;">${payload.address}</td></tr>
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b;">City / Region:</td><td style="padding: 6px 0;">${payload.city}, ${payload.region} ${payload.postalCode}</td></tr>
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b;">Country:</td><td style="padding: 6px 0; font-weight: bold;">${payload.country}</td></tr>
      </table>

      <h3 style="font-size: 14px; color: #0c1e3d; border-bottom: 2px solid #e2e8f0; padding-bottom: 6px; margin: 20px 0 10px; text-transform: uppercase;">Prize & Payout Details</h3>
      <table style="width: 100%; border-collapse: collapse; font-size: 13px;">
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b; width: 40%;">Prize Amount:</td><td style="padding: 6px 0; font-weight: bold; color: #15803d;">${payload.prizeAmount}</td></tr>
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b; width: 40%;">6 Winning Numbers:</td><td style="padding: 6px 0; font-weight: bold; color: #c81e28;">${payload.winningNumbers}</td></tr>
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b;">Payment Preference:</td><td style="padding: 6px 0; font-weight: bold;">${payoutText}</td></tr>
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b;">Digital Signature:</td><td style="padding: 6px 0; font-style: italic;">${payload.signature || formattedName}</td></tr>
        <tr style="border-bottom: 1px solid #f1f5f9;"><td style="padding: 6px 0; color: #64748b;">Special Notes:</td><td style="padding: 6px 0;">${payload.notes || "None"}</td></tr>
        <tr><td style="padding: 6px 0; color: #64748b;">Timestamp:</td><td style="padding: 6px 0;">${subDate}</td></tr>
      </table>
    </div>

    <div style="background: #f8fafc; border-top: 1px solid #e2e8f0; padding: 16px 24px; text-align: center; font-size: 11px; color: #94a3b8;">
      Powerball Claims Center Admin Intake · Logged to PostgreSQL
    </div>
  </div>
</body>
</html>
  `;

  const fromAddress = smtp.from || (smtp.user && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(smtp.user) ? smtp.user : `"Powerball Claims Center" <${adminAgentEmail}>`);

  console.log(`[EMAIL DISPATCH] Preparing email notifications for Ref: ${payload.reference}`);
  console.log(`[EMAIL DISPATCH] Claimant Destination: ${payload.email}`);
  console.log(`[EMAIL DISPATCH] Admin/Agent Destination: ${adminAgentEmail}`);

  if (smtp.host && smtp.user && smtp.pass) {
    try {
      const transporter = nodemailer.createTransport({
        host: smtp.host,
        port: smtp.port,
        secure: smtp.secure || smtp.port === 465,
        auth: {
          user: smtp.user,
          pass: smtp.pass,
        },
      });

      // 1. Send confirmation to Claimant
      await transporter.sendMail({
        from: fromAddress,
        to: payload.email,
        subject: `Powerball Claims Center: Official Claim File Confirmation [Ref: ${payload.reference}]`,
        html: claimantHtml,
      });
      console.log(`[EMAIL DISPATCH] Claimant confirmation successfully sent to ${payload.email}`);

      // 2. Send dossier to Admin / Agent
      await transporter.sendMail({
        from: fromAddress,
        to: adminAgentEmail,
        replyTo: payload.email,
        subject: `[NEW CLAIM SUBMISSION] Ref: ${payload.reference} - ${formattedName} (${payload.prizeAmount})`,
        html: adminHtml,
      });
      console.log(`[EMAIL DISPATCH] Admin dossier successfully sent to ${adminAgentEmail}`);

      return {
        sent: true,
        claimantSent: true,
        adminSent: true,
        claimantEmail: payload.email,
        adminEmail: adminAgentEmail,
      };
    } catch (sendErr) {
      console.error("[EMAIL DISPATCH ERROR] Failed sending via SMTP:", sendErr);
      return {
        sent: false,
        error: String(sendErr),
        claimantEmail: payload.email,
        adminEmail: adminAgentEmail,
      };
    }
  } else {
    console.log("[EMAIL DISPATCH INFO] SMTP credentials not set. Simulated notification logged.");
    return {
      sent: true,
      simulated: true,
      claimantEmail: payload.email,
      adminEmail: adminAgentEmail,
    };
  }
}
