import { NextRequest, NextResponse } from "next/server";
import crypto from "crypto";
import { prisma } from "@/lib/db";
import { sendEmail } from "@/lib/email-sender";
import { getSiteHostname, getSiteUrlFromRequest } from "@/lib/site-url";

const BRAND = {
  dark: "#2d2b28",
  accent: "#3d3a36",
  muted: "#8a8580",
  bg: "#f7f5f2",
  cardBg: "#ffffff",
  border: "#e8e4df",
  cta: "#2d2b28",
  ctaText: "#fafaf8",
  link: "#5c5650",
  font: "'Quicksand', 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
};

function resetEmailHtml(resetUrl: string, siteUrl: string) {
  const hostname = getSiteHostname(siteUrl);
  return `<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@400;500;600;700&display=swap" rel="stylesheet"/>
<title>Reset your password</title></head>
<body style="margin:0;padding:0;background-color:${BRAND.bg};font-family:${BRAND.font};-webkit-font-smoothing:antialiased;">
<div style="display:none;max-height:0;overflow:hidden;">Reset your Echo password&#847;&zwnj;&nbsp;</div>
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background-color:${BRAND.bg};">
<tr><td align="center" style="padding:40px 16px 32px;">
  <table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="max-width:520px;">
    <tr><td align="center" style="padding-bottom:32px;">
      <span style="font-family:${BRAND.font};font-size:20px;font-weight:700;color:${BRAND.dark};">Echo</span>
    </td></tr>
  </table>
  <table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="max-width:520px;background-color:${BRAND.cardBg};border-radius:16px;border:1px solid ${BRAND.border};box-shadow:0 1px 3px rgba(0,0,0,0.04);">
    <tr><td style="padding:48px 40px 44px;">
      <h1 style="margin:0 0 16px;font-family:${BRAND.font};font-size:24px;font-weight:700;color:${BRAND.dark};line-height:1.3;">Reset your password</h1>
      <div style="margin:0 0 32px;font-family:${BRAND.font};font-size:15px;color:${BRAND.accent};line-height:1.65;">
        <p style="margin:0 0 16px;">We received a request to reset the password for your Echo account. Click the button below to choose a new password.</p>
        <p style="margin:0;">If you didn't request this, you can safely ignore this email.</p>
      </div>
      <table role="presentation" cellpadding="0" cellspacing="0" width="100%"><tr><td>
        <a href="${resetUrl}" target="_blank" style="display:inline-block;padding:14px 32px;background-color:${BRAND.cta};color:${BRAND.ctaText};font-family:${BRAND.font};font-size:15px;font-weight:600;text-decoration:none;border-radius:10px;">Reset Password</a>
      </td></tr></table>
      <p style="margin:28px 0 0;font-family:${BRAND.font};font-size:13px;color:${BRAND.muted};line-height:1.55;">This link expires in 1 hour. If you didn't request a password reset, no action is needed.</p>
    </td></tr>
  </table>
  <table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="max-width:520px;">
    <tr><td align="center" style="padding:28px 0 8px;">
      <p style="margin:0;font-family:${BRAND.font};font-size:12px;color:${BRAND.muted};">AI-powered response card scanning for churches</p>
      <p style="margin:6px 0 0;font-family:${BRAND.font};font-size:12px;"><a href="${siteUrl}" style="color:${BRAND.link};text-decoration:underline;">${hostname}</a></p>
    </td></tr>
  </table>
</td></tr></table>
</body></html>`;
}

export async function POST(req: NextRequest) {
  try {
    const { email } = await req.json();

    if (!email || typeof email !== "string") {
      return NextResponse.json({ ok: true });
    }

    const user = await prisma.user.findUnique({ where: { email: email.toLowerCase().trim() } });

    if (user) {
      await prisma.passwordResetToken.deleteMany({ where: { email: user.email } });

      const token = crypto.randomUUID();
      await prisma.passwordResetToken.create({
        data: {
          email: user.email,
          token,
          expiresAt: new Date(Date.now() + 60 * 60 * 1000),
        },
      });

      const siteUrl = getSiteUrlFromRequest(req);
      const resetUrl = `${siteUrl}/reset-password?token=${token}`;
      await sendEmail(
        user.email,
        "Reset your password — Echo",
        resetEmailHtml(resetUrl, siteUrl)
      );
    }

    return NextResponse.json({ ok: true });
  } catch (error) {
    console.error("[forgot-password] Error:", error);
    return NextResponse.json({ ok: true });
  }
}
