import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { verifyAdminToken } from '@/lib/admin-auth'

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // Verify admin token
    const authResult = await verifyAdminToken(request)
    if (!authResult.success) {
      return NextResponse.json({ error: authResult.error }, { status: 401 })
    }

    const { id } = await params
    const service = await db.service.findUnique({
      where: { id },
      include: {
        children: {
          where: { status: 'ACTIVE' },
          orderBy: { position: 'asc' }
        }
      }
    })

    if (!service) {
      return NextResponse.json(
        { error: 'Layanan tidak ditemukan' },
        { status: 404 }
      )
    }

    // Clean invalid iconUrl
    const cleanedService = {
      ...service,
      iconUrl: (service.iconUrl && (service.iconUrl.startsWith('/') || service.iconUrl.startsWith('http'))) 
        ? service.iconUrl 
        : null
    }

    return NextResponse.json({
      success: true,
      service: cleanedService
    })
  } catch (error) {
    console.error('Error fetching service:', error)
    return NextResponse.json(
      { error: 'Terjadi kesalahan saat mengambil data layanan' },
      { status: 500 }
    )
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // Verify admin token
    const authResult = await verifyAdminToken(request)
    if (!authResult.success) {
      return NextResponse.json({ error: authResult.error }, { status: 401 })
    }

    const { id } = await params
    const body = await request.json()
    const { 
      title, 
      description, 
      category, 
      estimatedTime, 
      requirements, 
      iconUrl, 
      linkType, 
      linkUrl, 
      isNewTab, 
      status,
      parentId,
      position
    } = body

    // Validate required fields
    if (!title || !description) {
      return NextResponse.json(
        { error: 'Nama layanan dan deskripsi wajib diisi' },
        { status: 400 }
      )
    }

    // Validate linkType and parentId combination
    if (linkType === 'SUBMENU' && parentId) {
      // Child submenu with linkType SUBMENU should have children or linkUrl
      if (!linkUrl) {
        // It's okay - can be a grouping submenu without action
      }
    }

    // Validate external link
    if (linkType === 'EXTERNAL' && linkUrl) {
      // Support multiple URL schemes: http, https, tel, mailto, sms, whatsapp, etc.
      const validSchemes = [
        'http://',
        'https://',
        'tel:',
        'mailto:',
        'sms:',
        'whatsapp:',
        'wa.me/',
        'ftp://',
        'file://',
        'javascript:',
        'callto:'
      ]
      
      const isValidUrl = validSchemes.some(scheme => linkUrl.startsWith(scheme))
      
      if (!isValidUrl) {
        return NextResponse.json(
          { 
            error: 'Link eksternal harus dimulai dengan salah satu: http://, https://, tel:, mailto:, sms:, whatsapp:, wa.me/, ftp://, file://, javascript:, atau callto:' 
          },
          { status: 400 }
        )
      }
    }

    // Check if service exists
    const existingService = await db.service.findUnique({
      where: { id }
    })

    if (!existingService) {
      return NextResponse.json(
        { error: 'Layanan tidak ditemukan' },
        { status: 404 }
      )
    }

    // Generate new slug if title changed
    let slug = existingService.slug
    if (title !== existingService.title) {
      slug = title
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/(^-|-$)/g, '')

      // Check if new slug conflicts with other services
      const conflictingService = await db.service.findFirst({
        where: {
          slug,
          id: { not: id }
        }
      })

      if (conflictingService) {
        return NextResponse.json(
          { error: 'Layanan dengan nama serupa sudah ada' },
          { status: 400 }
        )
      }
    }

    const service = await db.service.update({
      where: { id },
      data: {
        title,
        slug,
        description,
        category: category || 'lainnya',
        estimatedTime: estimatedTime || '',
        requirements: requirements || [],
        iconUrl: iconUrl || null,
        linkType: linkType || 'INTERNAL',
        linkUrl: linkUrl || null,
        isNewTab: isNewTab || false,
        status: status || 'ACTIVE',
        parentId: parentId || null,
        position: position !== undefined ? position : existingService.position
      }
    })

    return NextResponse.json({
      success: true,
      service,
      message: 'Layanan berhasil diperbarui'
    })
  } catch (error) {
    console.error('Error updating service:', error)
    return NextResponse.json(
      { error: 'Terjadi kesalahan saat memperbarui layanan' },
      { status: 500 }
    )
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // Verify admin token
    const authResult = await verifyAdminToken(request)
    if (!authResult.success) {
      return NextResponse.json({ error: authResult.error }, { status: 401 })
    }

    const { id } = await params
    // Check if service exists
    const existingService = await db.service.findUnique({
      where: { id }
    })

    if (!existingService) {
      return NextResponse.json(
        { error: 'Layanan tidak ditemukan' },
        { status: 404 }
      )
    }

    // Check if service has related requests
    const requestCount = await db.serviceRequest.count({
      where: { serviceId: id }
    })

    if (requestCount > 0) {
      return NextResponse.json(
        { error: 'Tidak dapat menghapus layanan yang memiliki pengajuan terkait' },
        { status: 400 }
      )
    }

    // Check if service has children
    const childrenCount = await db.service.count({
      where: { parentId: id }
    })

    if (childrenCount > 0) {
      return NextResponse.json(
        { error: 'Tidak dapat menghapus layanan yang memiliki submenu' },
        { status: 400 }
      )
    }

    await db.service.delete({
      where: { id }
    })

    return NextResponse.json({
      success: true,
      message: 'Layanan berhasil dihapus'
    })
  } catch (error) {
    console.error('Error deleting service:', error)
    return NextResponse.json(
      { error: 'Terjadi kesalahan saat menghapus layanan' },
      { status: 500 }
    )
  }
}