import { Resend } from "resend";
import { logger } from "@/lib/logger";

let resendClient: Resend | null = null;

function getClient(): Resend {
  if (!resendClient) {
    const apiKey = process.env.RESEND_API_KEY;
    if (!apiKey) {
      throw new Error("RESEND_API_KEY not configured");
    }
    resendClient = new Resend(apiKey);
  }
  return resendClient;
}

export type EmailResult = {
  success: boolean;
  id?: string;
  error?: string;
};

const FROM_EMAIL = "RateRight <notifications@rateright.com.au>";

/**
 * Send an email via Resend
 */
export async function sendEmail(
  to: string,
  subject: string,
  html: string
): Promise<EmailResult> {
  if (!to || !to.includes("@")) {
    logger.warn(`Email skipped: invalid address "${to}"`);
    return { success: false, error: `Invalid email: ${to}` };
  }

  try {
    const client = getClient();
    const { data, error } = await client.emails.send({
      from: FROM_EMAIL,
      to,
      subject,
      html,
    });

    if (error) {
      logger.error(`Email failed to ${to}: ${error.message}`);
      return { success: false, error: error.message };
    }

    logger.info(`Email sent to ${to}: ID=${data?.id}`);
    return { success: true, id: data?.id };
  } catch (error) {
    const errMsg = error instanceof Error ? error.message : "Unknown email error";
    logger.error(`Email failed to ${to}: ${errMsg}`);
    return { success: false, error: errMsg };
  }
}

/**
 * Email templates for RateRight events
 */
function wrapTemplate(content: string): string {
  return `
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
<body style="margin:0;padding:0;background:#f5f5f5;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif">
  <div style="max-width:560px;margin:0 auto;padding:20px">
    <div style="background:#E06B20;height:4px;border-radius:2px;margin-bottom:20px"></div>
    <div style="background:#fff;border-radius:12px;padding:32px;box-shadow:0 1px 3px rgba(0,0,0,0.08)">
      ${content}
    </div>
    <div style="text-align:center;padding:20px;color:#999;font-size:12px">
      <strong style="color:#E06B20">RATERIGHT</strong> — Australia's $50 Construction Hiring Platform<br>
      <a href="https://rateright.com.au" style="color:#3B6FD4;text-decoration:none">rateright.com.au</a>
    </div>
  </div>
</body>
</html>`;
}

export const EMAIL_TEMPLATES = {
  workerHired: (workerName: string, jobTitle: string, contractorName: string) => ({
    subject: `🎉 You're Hired — ${jobTitle}`,
    html: wrapTemplate(`
      <h1 style="color:#1a1a1a;font-size:24px;margin:0 0 8px">You're Hired!</h1>
      <p style="color:#555;font-size:16px;margin:0 0 24px">Great news, ${workerName}!</p>
      <div style="background:#f0fdf4;border:2px solid #bbf7d0;border-radius:8px;padding:20px;margin-bottom:24px">
        <p style="margin:0;font-size:18px;font-weight:bold;color:#166534">${jobTitle}</p>
        <p style="margin:4px 0 0;color:#15803d">Hired by ${contractorName}</p>
      </div>
      <p style="color:#555;font-size:14px;margin:0 0 24px">
        Open the app to see contact details and get started. Your contractor is expecting to hear from you!
      </p>
      <a href="https://rateright.com.au/dashboard" style="display:inline-block;background:#E06B20;color:#fff;padding:14px 32px;border-radius:8px;text-decoration:none;font-weight:bold;font-size:16px">
        View Details
      </a>
    `),
  }),

  contractorMatchAlert: (contractorName: string, workerName: string, jobTitle: string) => ({
    subject: `New match for ${jobTitle} — ${workerName}`,
    html: wrapTemplate(`
      <h1 style="color:#1a1a1a;font-size:24px;margin:0 0 8px">New Worker Match</h1>
      <p style="color:#555;font-size:16px;margin:0 0 24px">G'day ${contractorName},</p>
      <div style="background:#eff6ff;border:2px solid #bfdbfe;border-radius:8px;padding:20px;margin-bottom:24px">
        <p style="margin:0;font-size:18px;font-weight:bold;color:#1e40af">${workerName}</p>
        <p style="margin:4px 0 0;color:#2563eb">Matched to your job: ${jobTitle}</p>
      </div>
      <p style="color:#555;font-size:14px;margin:0 0 24px">
        Review their profile and decide if they're the right fit.
      </p>
      <a href="https://rateright.com.au/contractor/matches" style="display:inline-block;background:#E06B20;color:#fff;padding:14px 32px;border-radius:8px;text-decoration:none;font-weight:bold;font-size:16px">
        View Match
      </a>
    `),
  }),

  welcomeWorker: (name: string) => ({
    subject: "Welcome to RateRight 🏗️",
    html: wrapTemplate(`
      <h1 style="color:#1a1a1a;font-size:24px;margin:0 0 8px">Welcome to RateRight!</h1>
      <p style="color:#555;font-size:16px;margin:0 0 24px">G'day ${name},</p>
      <p style="color:#555;font-size:14px;margin:0 0 16px">
        Your profile is live. Contractors can now find you and offer work. Here's what to do next:
      </p>
      <ol style="color:#555;font-size:14px;margin:0 0 24px;padding-left:20px">
        <li style="margin-bottom:8px"><strong>Complete your profile</strong> — add your trades, experience, and certifications</li>
        <li style="margin-bottom:8px"><strong>Upload your White Card</strong> — verified workers get hired faster</li>
        <li style="margin-bottom:8px"><strong>Browse jobs</strong> — apply to jobs that match your skills</li>
      </ol>
      <a href="https://rateright.com.au/worker/profile" style="display:inline-block;background:#E06B20;color:#fff;padding:14px 32px;border-radius:8px;text-decoration:none;font-weight:bold;font-size:16px">
        Complete Profile
      </a>
    `),
  }),

  welcomeContractor: (name: string) => ({
    subject: "Welcome to RateRight 🏗️",
    html: wrapTemplate(`
      <h1 style="color:#1a1a1a;font-size:24px;margin:0 0 8px">Welcome to RateRight!</h1>
      <p style="color:#555;font-size:16px;margin:0 0 24px">G'day ${name},</p>
      <p style="color:#555;font-size:14px;margin:0 0 16px">
        You're all set to find construction workers. Here's how it works:
      </p>
      <ol style="color:#555;font-size:14px;margin:0 0 24px;padding-left:20px">
        <li style="margin-bottom:8px"><strong>Post a job</strong> — describe what you need, AI handles the rest</li>
        <li style="margin-bottom:8px"><strong>Review matches</strong> — we'll match you with qualified workers</li>
        <li style="margin-bottom:8px"><strong>Hire for $50</strong> — flat fee, no subscriptions, no agency markup</li>
      </ol>
      <a href="https://rateright.com.au/contractor/post-job" style="display:inline-block;background:#E06B20;color:#fff;padding:14px 32px;border-radius:8px;text-decoration:none;font-weight:bold;font-size:16px">
        Post Your First Job
      </a>
    `),
  }),
} as const;
