import { NextRequest, NextResponse } from 'next/server'

export const config = {
  api: {
    bodyParser: false,
  },
}

const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN as string
const TELEGRAM_CHAT_ID = process.env.TELEGRAM_CHAT_ID as string

export async function POST(req: NextRequest) {
  try {
    // Получаем formData из запроса
    const formData = await req.formData()
    // const file = formData.get('file')
    const name = formData.get('name')
    const phone = formData.get('phone')
    const email = formData.get('email')
    const additional = formData.get('additional')
    const lastName = formData.get('lastName')
    const departure = formData.get('departure')
    const pickUpDate = formData.get('pickUpDate')
    const pickUpTime = formData.get('pickUpTime')
    const returnLocation = formData.get('returnLocation')
    const returnDate = formData.get('returnDate')
    const returnTime = formData.get('returnTime')
    const childSeat = formData.get('childSeat') === 'true'
    const transfer = formData.get('transfer') === 'true'
    const withDriver = formData.get('withDriver') === 'true'
    const paymentMethod = formData.get('paymentMethod')
    const totalPrice = formData.get('totalPrice')

    const options =
      [
        childSeat ? 'Child seat' : null,
        transfer ? 'Transfer' : null,
        withDriver ? 'With driver' : null,
      ]
        .filter(Boolean)
        .join(', ') || 'None'

    // Преобразуем только если значение есть
    const pickUpDateObj = pickUpDate ? new Date(pickUpDate as string) : null
    const pickUpTimeObj = pickUpTime ? new Date(pickUpTime as string) : null
    const returnDateObj = returnDate ? new Date(returnDate as string) : null
    const returnTimeObj = returnTime ? new Date(returnTime as string) : null

    function formatDateTime(dateObj: Date | null, timeObj: Date | null) {
      if (!dateObj) return ''
      // Получаем дату: Fri Jul 18 2025
      const dateStr = dateObj.toLocaleDateString('en-US', {
        weekday: 'short',
        month: 'short',
        day: '2-digit',
        year: 'numeric',
      })
      // Получаем время: 12am
      let timeStr = ''
      if (timeObj) {
        timeStr = timeObj
          .toLocaleTimeString('en-US', { hour: 'numeric', hour12: true })
          .replace(':00', '')
          .toLowerCase()
      }
      return `${dateStr}${timeStr ? ' ' + timeStr : ''}`
    }

    const pickUpStr = formatDateTime(pickUpDateObj, pickUpTimeObj)
    const returnStr = formatDateTime(returnDateObj, returnTimeObj)
    // Формируем текст сообщения
    const caption =
      `🚗 New booking request\n` +
      (name ? `👤 Name: ${name} ${lastName ? lastName : ''}\n` : '') +
      (phone ? `📱 Phone: ${phone}\n` : '') +
      (email ? `✉️ Email: ${email}\n` : '') +
      (departure ? `📍 Pick-up: ${departure}${pickUpStr ? ', ' + pickUpStr : ''}\n` : '') +
      (returnLocation ? `🏁 Return: ${returnLocation}${returnStr ? ', ' + returnStr : ''}\n` : '') +
      `🛠️ Options: ${options}\n` +
      (paymentMethod ? `💳 Payment: ${paymentMethod}\n` : '') +
      (totalPrice ? `💰 Total: ${totalPrice}\n` : '') +
      (additional ? `💬 Comment: ${additional}` : '')

    // Собираем FormData для Telegram
    // const tgFormData = new FormData()
    // tgFormData.append('chat_id', TELEGRAM_CHAT_ID)
    // tgFormData.append('caption', caption)

    // Отправляем caption как обычное сообщение
    const textRes = await fetch(`https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        chat_id: TELEGRAM_CHAT_ID,
        text: caption,
      }),
    })

    if (!textRes.ok) {
      const err = await textRes.json()
      return NextResponse.json({ ok: false, error: err }, { status: 500 })
    }

    // Отправляем документы по одному
    const files: File[] = []
    formData.forEach((value, key) => {
      if (
        key.startsWith('documents') &&
        value instanceof Blob &&
        typeof (value as any).name === 'string'
      ) {
        files.push(value as File)
      }
    })

    for (const file of files) {
      const fileForm = new FormData()
      fileForm.append('chat_id', TELEGRAM_CHAT_ID)
      fileForm.append('document', file, file.name)

      const fileRes = await fetch(
        `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendDocument`,
        {
          method: 'POST',
          body: fileForm,
        },
      )

      if (!fileRes.ok) {
        const err = await fileRes.json()
        return NextResponse.json({ ok: false, error: err }, { status: 500 })
      }
    }

    return NextResponse.json({ ok: true })
  } catch (e: unknown) {
    const errorMessage = e instanceof Error ? e.message : JSON.stringify(e)
    console.error('Telegram API error:', e)
    return NextResponse.json({ ok: false, error: errorMessage }, { status: 500 })
  }
}
