import { serve } from "https://deno.land/std@0.168.0/http/server.ts";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};

serve(async (req) => {
  if (req.method === "OPTIONS") {
    return new Response("ok", { headers: corsHeaders });
  }

  try {
    const { to, name, username, password, role, dept } = await req.json();

    const RESEND_API_KEY = Deno.env.get("RESEND_API_KEY");
    const FROM_EMAIL = Deno.env.get("FROM_EMAIL") || "noreply@uwezofund.go.ke";
    const ORG_NAME = "Uwezo Fund Oversight Board";

    const roleLabel: Record<string, string> = {
      admin: "System Administrator",
      hr: "HR Manager",
      hod: "Head of Department",
      hos: "Head of Secretariat",
      finance: "Finance Officer",
      employee: "Staff Member",
      intern: "Intern",
    };

    const htmlBody = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <style>
    body { font-family: Tahoma, sans-serif; background: #f5f5f5; margin: 0; padding: 20px; }
    .container { max-width: 600px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.1); }
    .header { background: linear-gradient(135deg, #b828a0, #8b1a7a); padding: 32px; text-align: center; }
    .header h1 { color: white; margin: 0; font-size: 22px; }
    .header p { color: rgba(255,255,255,0.85); margin: 8px 0 0; font-size: 14px; }
    .body { padding: 32px; }
    .greeting { font-size: 16px; color: #333; margin-bottom: 16px; }
    .credentials { background: #fdf4fc; border: 2px solid #e8a8e0; border-radius: 10px; padding: 20px; margin: 20px 0; }
    .credentials h3 { color: #b828a0; margin: 0 0 14px; font-size: 14px; text-transform: uppercase; letter-spacing: 1px; }
    .cred-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #f0d0ec; }
    .cred-row:last-child { border-bottom: none; }
    .cred-label { color: #777; font-size: 13px; }
    .cred-value { font-weight: bold; color: #333; font-size: 13px; font-family: 'Courier New', monospace; }
    .warning { background: #fff8e1; border-left: 4px solid #f59e0b; padding: 14px 16px; border-radius: 6px; margin: 20px 0; }
    .warning p { color: #78350f; font-size: 13px; margin: 0; line-height: 1.6; }
    .steps { margin: 20px 0; }
    .steps h4 { color: #444; font-size: 14px; margin-bottom: 12px; }
    .step { display: flex; align-items: flex-start; gap: 10px; margin: 8px 0; }
    .step-num { background: #b828a0; color: white; border-radius: 50%; width: 22px; height: 22px; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: bold; flex-shrink: 0; }
    .step-text { color: #555; font-size: 13px; line-height: 1.5; padding-top: 2px; }
    .footer { background: #f9f9f9; padding: 20px 32px; border-top: 1px solid #eee; text-align: center; }
    .footer p { color: #999; font-size: 12px; margin: 4px 0; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>${ORG_NAME}</h1>
      <p>Human Resource Management System — Account Setup</p>
    </div>
    <div class="body">
      <p class="greeting">Dear <strong>${name}</strong>,</p>
      <p style="color:#555; font-size:14px; line-height:1.6;">
        Welcome to the ${ORG_NAME} HR Management System. Your account has been created.
        ${dept ? `You have been assigned to the <strong>${dept}</strong> department as <strong>${roleLabel[role] || role}</strong>.` : `Your system role is <strong>${roleLabel[role] || role}</strong>.`}
      </p>
      
      <div class="credentials">
        <h3>🔐 Your Login Credentials</h3>
        <div class="cred-row">
          <span class="cred-label">Username / Employee ID</span>
          <span class="cred-value">${username}</span>
        </div>
        <div class="cred-row">
          <span class="cred-label">Temporary Password</span>
          <span class="cred-value">${password}</span>
        </div>
        <div class="cred-row">
          <span class="cred-label">System Role</span>
          <span class="cred-value">${roleLabel[role] || role}</span>
        </div>
        ${dept ? `<div class="cred-row"><span class="cred-label">Department</span><span class="cred-value">${dept}</span></div>` : ''}
      </div>

      <div class="warning">
        <p><strong>⚠ Important:</strong> This is a temporary password. You will be required to change it on your first login. Please do not share these credentials with anyone.</p>
      </div>

      <div class="steps">
        <h4>Getting Started:</h4>
        <div class="step">
          <div class="step-num">1</div>
          <div class="step-text">Navigate to the HRMS login page</div>
        </div>
        <div class="step">
          <div class="step-num">2</div>
          <div class="step-text">Enter the username and temporary password above</div>
        </div>
        <div class="step">
          <div class="step-num">3</div>
          <div class="step-text">You will be prompted to create a new secure password</div>
        </div>
        <div class="step">
          <div class="step-num">4</div>
          <div class="step-text">Complete your profile setup and explore your dashboard</div>
        </div>
      </div>
    </div>
    <div class="footer">
      <p>This is an automated message from the ${ORG_NAME} HR System.</p>
      <p>If you did not expect this email, please contact the HR department immediately.</p>
    </div>
  </div>
</body>
</html>`;

    let emailSent = false;
    let emailError = "";

    if (RESEND_API_KEY) {
      try {
        const resendRes = await fetch("https://api.resend.com/emails", {
          method: "POST",
          headers: {
            "Authorization": `Bearer ${RESEND_API_KEY}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            from: `${ORG_NAME} HR <${FROM_EMAIL}>`,
            to: [to],
            subject: `Welcome to ${ORG_NAME} HRMS — Your Account Credentials`,
            html: htmlBody,
          }),
        });

        if (resendRes.ok) {
          emailSent = true;
        } else {
          const errData = await resendRes.json();
          emailError = JSON.stringify(errData);
        }
      } catch (e) {
        emailError = String(e);
      }
    } else {
      emailError = "RESEND_API_KEY not configured. Add it to Supabase Edge Function secrets to enable email sending.";
      console.log(`[WELCOME EMAIL] Would send to: ${to}`);
      console.log(`[WELCOME EMAIL] Username: ${username}, Password: ${password}`);
    }

    return new Response(
      JSON.stringify({
        success: true,
        emailSent,
        emailError: emailError || undefined,
        message: emailSent
          ? `Welcome email sent to ${to}`
          : `Account created. Email not sent: ${emailError}`,
      }),
      {
        headers: { ...corsHeaders, "Content-Type": "application/json" },
        status: 200,
      }
    );
  } catch (error) {
    return new Response(
      JSON.stringify({ success: false, error: String(error) }),
      { headers: { ...corsHeaders, "Content-Type": "application/json" }, status: 400 }
    );
  }
});
