/* eslint-disable @typescript-eslint/no-explicit-any */
import { NextResponse } from 'next/server';
import { headers } from 'next/headers';
import { stripe } from '@/lib/stripe';
import { Resend } from 'resend';

const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
const resend = new Resend(process.env.RESEND_API_KEY);

export async function POST(req: Request) {
  const body = await req.text();
  const sig = (await headers()).get('stripe-signature') as string;

  let event;

  try {
    if (!sig || !webhookSecret) {
      return NextResponse.json({ error: 'Missing signature or secret' }, { status: 400 });
    }
    event = stripe.webhooks.constructEvent(body, sig, webhookSecret);
  } catch (err: any) {
    console.error(`Webhook Error: ${err.message}`);
    return NextResponse.json({ error: `Webhook Error: ${err.message}` }, { status: 400 });
  }

  if (event.type === 'checkout.session.completed') {
    const session = event.data.object as any;

    const customerEmail = session.customer_details?.email;
    const customerName = session.customer_details?.name || 'there';
    const amountTotal = (session.amount_total / 100).toFixed(2);
    const portalUrl = process.env.NEXT_PUBLIC_LOGIN_PORTAL_URL;

    try {
      // 1. Send welcome email to customer
      const customerEmailResult = await resend.emails.send({
        from: 'DesignShare <hello@designshare.net>',
        to: customerEmail,
        subject: 'Welcome to DesignShare! Your subscription is active 🎉',
        html: `
          <div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; color: #1a1916;">
            <div style="padding: 40px 0 20px;">
              <h1 style="font-size: 28px; font-weight: 400; margin-bottom: 8px;">Welcome to DesignShare, ${customerName}!</h1>
              <p style="color: #6b6760; font-size: 15px; line-height: 1.6;">Your Monthly Partner subscription is now active. Here's your payment summary:</p>
            </div>
            <div style="background: #faf9f7; border: 1px solid #e8e5e0; border-radius: 12px; padding: 24px; margin: 24px 0;">
              <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #f0ede8;">
                <span style="color: #9a9890; font-size: 13px;">Plan</span>
                <span style="font-size: 13px;">Monthly Partner</span>
              </div>
              <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #f0ede8;">
                <span style="color: #9a9890; font-size: 13px;">Amount charged</span>
                <span style="font-size: 13px; font-weight: 500;">$${amountTotal}</span>
              </div>
              <div style="display: flex; justify-content: space-between; padding: 10px 0;">
                <span style="color: #9a9890; font-size: 13px;">Billing</span>
                <span style="font-size: 13px;">Monthly</span>
              </div>
            </div>
            <div style="margin: 32px 0;">
              <p style="font-size: 14px; color: #4a4845; line-height: 1.6;"><strong>What happens next:</strong></p>
              <p style="font-size: 14px; color: #6b6760; line-height: 1.6;">1. Your project manager will reach out within the hour to set up your Notion board or Slack channel.</p>
              <p style="font-size: 14px; color: #6b6760; line-height: 1.6;">2. Queue your first design request — landing pages, app UI, Webflow builds, brand work.</p>
              <p style="font-size: 14px; color: #6b6760; line-height: 1.6;">3. First delivery in ~48 hours with unlimited revisions.</p>
            </div>
            <div style="text-align: center; margin: 32px 0;">
              <a href="${portalUrl}" style="background: #1a1916; color: #ffffff; padding: 14px 32px; border-radius: 8px; text-decoration: none; font-size: 14px; font-weight: 500;">Access your member portal →</a>
            </div>
            <div style="border-top: 1px solid #f0ede8; padding-top: 20px; margin-top: 32px;">
              <p style="font-size: 12px; color: #b0ada6; text-align: center;">Questions? Contact us at <a href="mailto:hello@designshare.net" style="color: #6b6760;">hello@designshare.net</a></p>
              <p style="font-size: 12px; color: #b0ada6; text-align: center; margin-top: 4px;">DesignShare by Elegant IT Limited</p>
            </div>
          </div>
        `,
      });
      if (customerEmailResult.error) {
        console.error(
          '[stripe-webhook] customer welcome email FAILED:',
          customerEmailResult.error,
        );
      } else {
        console.log(
          '[stripe-webhook] customer welcome sent:',
          customerEmailResult.data?.id,
          '->',
          customerEmail,
        );
      }

      // 2. Send admin notification
      const adminEmailResult = await resend.emails.send({
        from: 'DesignShare Alerts <hello@designshare.net>',
        to: 'designshareltd@gmail.com',
        subject: `🎉 New Subscription! ${customerName} just subscribed — $${amountTotal}`,
        html: `
          <div style="font-family: sans-serif; max-width: 600px; margin: 0 auto;">
            <h2 style="font-size: 22px; font-weight: 400;">New Subscription Received</h2>
            <div style="background: #faf9f7; border: 1px solid #e8e5e0; border-radius: 12px; padding: 24px; margin: 20px 0;">
              <p style="margin: 8px 0;"><strong>Customer:</strong> ${customerName}</p>
              <p style="margin: 8px 0;"><strong>Email:</strong> ${customerEmail}</p>
              <p style="margin: 8px 0;"><strong>Amount:</strong> $${amountTotal}</p>
              <p style="margin: 8px 0;"><strong>Session ID:</strong> ${session.id}</p>
            </div>
          </div>
        `,
      });
      if (adminEmailResult.error) {
        console.error(
          '[stripe-webhook] admin notification email FAILED:',
          adminEmailResult.error,
        );
      } else {
        console.log(
          '[stripe-webhook] admin notification sent:',
          adminEmailResult.data?.id,
        );
      }
    } catch (emailError) {
      // Network/throw-level failure. Logged for visibility; we still return 200
      // to Stripe so it does not retry the whole webhook (which would re-send
      // any email that already succeeded).
      console.error('[stripe-webhook] Error sending emails:', emailError);
    }
  }

  return NextResponse.json({ received: true });
}
