import { NextResponse } from 'next/server'
import mongoose from 'mongoose'
import connectToDatabase from '@/lib/db'
import DemoRegistrationModel from '@/lib/models/demo-registration'
import DemoModel from '@/lib/models/demo'
import { sendEmail } from '@/lib/mail'

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { demoId, name, email, phone, organization, role, preferredDate, message, slotId } = body

    if (!demoId || !name || !email) {
      return NextResponse.json({ message: 'Missing required fields' }, { status: 400 })
    }

    await connectToDatabase()

    const Demo = mongoose.models.demos || DemoModel(mongoose)
    const demo = await Demo.findById(demoId)
    if (!demo) {
      return NextResponse.json({ message: 'Demo session not found' }, { status: 404 })
    }

    const DemoRegistration = mongoose.models.demo_registrations || DemoRegistrationModel(mongoose)
    const newRegistration = new DemoRegistration({
      demoId,
      name,
      email,
      phone: phone || '',
      organization: organization || '',
      role: role || '',
      preferredDate: preferredDate || '',
      message: message || '',
      slotId: slotId || '',
      status: 'Confirmed'
    })

    // Format demo date and time for the email
    let demoTimeStr = `${demo.date} at ${demo.startTime}`
    if (demo.slotsEnabled && demo.slots && slotId) {
      const selectedSlot = demo.slots.find((s: any) => s.slotId === slotId)
      if (selectedSlot) {
        const slotDate = selectedSlot.date || demo.date
        const slotStartTime = selectedSlot.startTime || demo.startTime
        const slotEndTime = selectedSlot.endTime || demo.endTime || ''
        demoTimeStr = `${slotDate} at ${slotStartTime}${slotEndTime ? ` - ${slotEndTime}` : ''}`
      }
    }
    if (demo.timezone) {
      demoTimeStr += ` (${demo.timezone})`
    }

    const meetLink = demo.googleMeetLink || 'Will be shared before the demo starts.'

    const emailSubject = `Demo Registered: ${demo.title}`
    const emailText = `Hello ${name || 'there'},\n\nYou have successfully registered for the demo session.\n\nDemo: ${demo.title}\nTime: ${demoTimeStr}\nGoogle Meet Link: ${meetLink}\n\nLooking forward to meeting you!\n\nBest regards,\nThe CodeframeAI Team`
    const emailHtml = `
      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 5px;">
        <h2 style="color: #2d9895; margin-bottom: 20px;">Demo Session Confirmed!</h2>
        <p>Hello <strong>${name || 'there'}</strong>,</p>
        <p>You have successfully registered for a personalized CodeframeAI demo session:</p>
        <div style="background-color: #f9f9f9; padding: 15px; border-left: 4px solid #2d9895; margin: 20px 0;">
          <h3 style="margin-top: 0; color: #333;">${demo.title}</h3>
          <p style="margin: 5px 0;"><strong>Time:</strong> ${demoTimeStr}</p>
          <p style="margin: 5px 0;"><strong>Google Meet Link:</strong> <a href="${meetLink}" target="_blank">${meetLink}</a></p>
        </div>
        <p>We look forward to demonstrating CodeframeAI to you. If you have any questions, feel free to reply to this email.</p>
        <br/>
        <p>Best regards,</p>
        <p><strong>The CodeframeAI Team</strong></p>
      </div>
    `

    try {
      const emailResult = await sendEmail({
        to: email.trim().toLowerCase(),
        subject: emailSubject,
        text: emailText,
        html: emailHtml
      })

      if (emailResult?.success) {
        newRegistration.confirmationEmailSentAt = new Date()
      } else {
        console.error('[Registration] Demo confirmation email not successful:', emailResult)
      }
    } catch (emailError) {
      console.error('[Registration] Demo confirmation email failed:', emailError)
    }

    await newRegistration.save()

    return NextResponse.json({ message: 'Registration successful', registration: newRegistration }, { status: 201 })
  } catch (error: any) {
    console.error(error)
    return NextResponse.json({ message: 'Error creating registration', error: error.message || String(error) }, { status: 500 })
  }
}

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url)
  const demoId = searchParams.get('demoId')

  if (!demoId) {
    return NextResponse.json({ message: 'demoId is required' }, { status: 400 })
  }

  try {
    await connectToDatabase()

    const registrations = await DemoRegistrationModel(mongoose).find({ demoId })

    return NextResponse.json({ registrations })
  } catch (error: any) {
    console.error(error)
    return NextResponse.json({ message: 'Error fetching registrations', error: error.message || String(error) }, { status: 500 })
  }
}
