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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const authResult = await requireAuth(['ADMIN'])(request)
    if ('error' in authResult) return authResult.error

    const { id } = await params

    const user = await db.user.findUnique({
      where: { id },
      select: {
        id: true,
        email: true,
        name: true,
        company: true,
        phone: true,
        role: true,
        isActive: true,
        createdAt: true,
        updatedAt: true,
        assignedById: true,
        assignedBy: { select: { id: true, name: true, email: true } },
        _count: {
          select: {
            reviews: true,
            assignedReviews: true,
            supervisorResponses: true,
            customers: true,
            notifications: true,
          },
        },
      },
    })

    if (!user) {
      return NextResponse.json(
        { error: 'Usuario no encontrado' },
        { status: 404 }
      )
    }

    return NextResponse.json({ user })
  } catch (error) {
    console.error('Error al obtener usuario:', error)
    return NextResponse.json(
      { error: 'Error interno del servidor' },
      { status: 500 }
    )
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const authResult = await requireAuth(['ADMIN'])(request)
    if ('error' in authResult) return authResult.error

    const { user: adminUser } = authResult
    const { id } = await params
    const body = await request.json()
    const { name, email, phone, company, role, isActive } = body

    const existingUser = await db.user.findUnique({ where: { id } })

    if (!existingUser) {
      return NextResponse.json(
        { error: 'Usuario no encontrado' },
        { status: 404 }
      )
    }

    // Cannot change own role
    if (role !== undefined && id === adminUser.id && role !== existingUser.role) {
      return NextResponse.json(
        { error: 'No puede cambiar su propio rol' },
        { status: 400 }
      )
    }

    // Cannot deactivate self
    if (isActive === false && id === adminUser.id) {
      return NextResponse.json(
        { error: 'No puede desactivar su propia cuenta' },
        { status: 400 }
      )
    }

    // Cannot deactivate the last ADMIN
    if (isActive === false && existingUser.role === 'ADMIN') {
      const adminCount = await db.user.count({
        where: { role: 'ADMIN', isActive: true },
      })
      if (adminCount <= 1) {
        return NextResponse.json(
          { error: 'No puede desactivar el último usuario ADMIN' },
          { status: 400 }
        )
      }
    }

    // Cannot change the last ADMIN's role
    if (role !== undefined && role !== 'ADMIN' && existingUser.role === 'ADMIN') {
      const adminCount = await db.user.count({
        where: { role: 'ADMIN', isActive: true },
      })
      if (adminCount <= 1) {
        return NextResponse.json(
          { error: 'No puede cambiar el rol del último usuario ADMIN' },
          { status: 400 }
        )
      }
    }

    // Validate role value
    if (role !== undefined) {
      const validRoles = ['CUSTOMER', 'SUPERVISOR', 'MANAGER', 'ADMIN']
      if (!validRoles.includes(role)) {
        return NextResponse.json(
          { error: 'Rol inválido' },
          { status: 400 }
        )
      }
    }

    // Check email uniqueness if changing
    if (email !== undefined) {
      const trimmedEmail = email.toLowerCase().trim()
      if (trimmedEmail !== existingUser.email) {
        const emailExists = await db.user.findUnique({
          where: { email: trimmedEmail },
        })
        if (emailExists) {
          return NextResponse.json(
            { error: 'Ya existe una cuenta con este email' },
            { status: 409 }
          )
        }
      }
    }

    const updateData: {
      name?: string
      email?: string
      phone?: string | null
      company?: string | null
      role?: string
      isActive?: boolean
    } = {}

    if (name !== undefined) updateData.name = name.trim()
    if (email !== undefined) updateData.email = email.toLowerCase().trim()
    if (phone !== undefined) updateData.phone = phone?.trim() || null
    if (company !== undefined) updateData.company = company?.trim() || null
    if (role !== undefined) updateData.role = role
    if (isActive !== undefined) updateData.isActive = isActive

    const updated = await db.user.update({
      where: { id },
      data: updateData,
      select: {
        id: true,
        email: true,
        name: true,
        company: true,
        phone: true,
        role: true,
        isActive: true,
        createdAt: true,
        updatedAt: true,
        assignedBy: { select: { id: true, name: true } },
      },
    })

    return NextResponse.json({ user: updated })
  } catch (error) {
    console.error('Error al actualizar usuario:', error)
    return NextResponse.json(
      { error: 'Error interno del servidor' },
      { status: 500 }
    )
  }
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const authResult = await requireAuth(['ADMIN'])(request)
    if ('error' in authResult) return authResult.error

    const { user: adminUser } = authResult
    const { id } = await params
    const body = await request.json()
    const { activate } = body

    if (activate === undefined || activate === null) {
      return NextResponse.json(
        { error: 'El campo "activate" es requerido' },
        { status: 400 }
      )
    }

    const existingUser = await db.user.findUnique({ where: { id } })

    if (!existingUser) {
      return NextResponse.json(
        { error: 'Usuario no encontrado' },
        { status: 404 }
      )
    }

    // Cannot deactivate self
    if (!activate && id === adminUser.id) {
      return NextResponse.json(
        { error: 'No puede desactivar su propia cuenta' },
        { status: 400 }
      )
    }

    // Cannot deactivate the last ADMIN
    if (!activate && existingUser.role === 'ADMIN') {
      const adminCount = await db.user.count({
        where: { role: 'ADMIN', isActive: true },
      })
      if (adminCount <= 1) {
        return NextResponse.json(
          { error: 'No puede desactivar el último usuario ADMIN' },
          { status: 400 }
        )
      }
    }

    const updated = await db.user.update({
      where: { id },
      data: { isActive: !!activate },
      select: {
        id: true,
        email: true,
        name: true,
        role: true,
        isActive: true,
      },
    })

    return NextResponse.json({ user: updated })
  } catch (error) {
    console.error('Error al cambiar estado de usuario:', error)
    return NextResponse.json(
      { error: 'Error interno del servidor' },
      { status: 500 }
    )
  }
}
