import { NextRequest, NextResponse } from "next/server";
import { requireStaffAuth } from "@/lib/staff-auth";
import { prisma } from "@/lib/db";
import { createId } from "@paralleldrive/cuid2";
import { getDataSource } from "@/lib/data-source";

interface RouteParams {
  params: { id: string };
}

/**
 * GET /api/staff/dashboard/waitlists/[id]/signups
 * List all signups for a waitlist (with pagination)
 */
export async function GET(request: NextRequest, { params }: RouteParams) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id: waitlistId } = params;
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get("page") || "1");
    const limit = parseInt(searchParams.get("limit") || "50");
    const search = searchParams.get("search");

    // Convex branch
    if (getDataSource("leads") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");

        // Verify waitlist exists
        const waitlist = await convexQuery("bookings/queries:getWaitlistById", {
          id: waitlistId as any,
        });

        if (!waitlist) {
          return NextResponse.json(
            { error: "Waitlist not found" },
            { status: 404 },
          );
        }

        const skip = (page - 1) * limit;
        const signupsResult = (await convexQuery(
          "bookings/queries:getWaitlistSignups",
          {
            waitlistId,
            limit,
            offset: skip,
          },
        )) as any;

        let signups = signupsResult?.signups ?? [];

        // Client-side search filtering
        if (search) {
          const term = search.toLowerCase();
          signups = signups.filter(
            (s: any) =>
              s.name?.toLowerCase().includes(term) ||
              s.email?.toLowerCase().includes(term) ||
              s.mobile?.includes(term),
          );
        }

        const totalCount = signupsResult?.total ?? 0;

        return NextResponse.json({
          signups,
          pagination: {
            page,
            limit,
            total: totalCount,
            totalPages: Math.ceil(totalCount / limit),
            hasMore: skip + signups.length < totalCount,
          },
        });
      } catch (convexError) {
        console.error(
          "Convex waitlist signups fetch failed, falling back to Prisma:",
          convexError,
        );
        // Fall through to Prisma
      }
    }

    // Check waitlist exists
    const waitlist = await prisma.waitlists.findUnique({
      where: { id: waitlistId },
    });

    if (!waitlist) {
      return NextResponse.json(
        { error: "Waitlist not found" },
        { status: 404 },
      );
    }

    // Build where clause
    const where: any = { waitlistId };
    if (search) {
      where.OR = [
        { name: { contains: search, mode: "insensitive" } },
        { email: { contains: search, mode: "insensitive" } },
        { mobile: { contains: search, mode: "insensitive" } },
      ];
    }

    const skip = (page - 1) * limit;

    const [signups, totalCount] = await Promise.all([
      prisma.waitlist_signups.findMany({
        where,
        orderBy: { createdAt: "desc" },
        skip,
        take: limit,
        include: {
          user: {
            select: {
              id: true,
              name: true,
              email: true,
              companyName: true,
            },
          },
        },
      }),
      prisma.waitlist_signups.count({ where }),
    ]);

    return NextResponse.json({
      signups,
      pagination: {
        page,
        limit,
        total: totalCount,
        totalPages: Math.ceil(totalCount / limit),
        hasMore: skip + signups.length < totalCount,
      },
    });
  } catch (error) {
    console.error("Failed to fetch waitlist signups:", error);
    return NextResponse.json(
      { error: "Failed to fetch signups" },
      { status: 500 },
    );
  }
}

// Simple email validation
function isValidEmail(email: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

// Simple mobile validation (allows various formats)
function isValidMobile(mobile: string): boolean {
  const cleaned = mobile.replace(/[\s\-\(\)]/g, "");
  return /^\+?\d{8,15}$/.test(cleaned);
}

/**
 * POST /api/staff/dashboard/waitlists/[id]/signups
 * Staff manually adds a user to a waitlist
 */
export async function POST(request: NextRequest, { params }: RouteParams) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id: waitlistId } = params;
    const body = await request.json();
    const { name, email, mobile, notes } = body;

    // Validate required fields
    if (!name || typeof name !== "string" || name.trim().length === 0) {
      return NextResponse.json({ error: "Name is required" }, { status: 400 });
    }

    if (!email || typeof email !== "string" || !isValidEmail(email.trim())) {
      return NextResponse.json(
        { error: "Valid email is required" },
        { status: 400 },
      );
    }

    if (
      !mobile ||
      typeof mobile !== "string" ||
      !isValidMobile(mobile.trim())
    ) {
      return NextResponse.json(
        { error: "Valid mobile number is required" },
        { status: 400 },
      );
    }

    // Convex branch
    if (getDataSource("leads") === "convex") {
      try {
        const { convexMutation, convexQuery } =
          await import("@/lib/convex-client");

        // Check waitlist exists
        const waitlist = await convexQuery("bookings/queries:getWaitlistById", {
          id: waitlistId as any,
        });

        if (!waitlist) {
          return NextResponse.json(
            { error: "Waitlist not found" },
            { status: 404 },
          );
        }

        const convexId = await convexMutation(
          "bookings/mutations:createWaitlistEntry",
          {
            waitlistId,
            name: name.trim(),
            email: email.trim().toLowerCase(),
            mobile: mobile.trim(),
            notes: notes?.trim() || undefined,
            addedBy: staffUser.id,
          },
        );

        return NextResponse.json({
          success: true,
          message: "User added to waitlist successfully",
          signup: {
            id: convexId,
            name: name.trim(),
            email: email.trim().toLowerCase(),
            mobile: mobile.trim(),
            createdAt: new Date().toISOString(),
          },
        });
      } catch (convexError) {
        console.error(
          "Convex waitlist signup create failed, falling back to Prisma:",
          convexError,
        );
        // Fall through to Prisma
      }
    }

    // Check waitlist exists
    const waitlist = await prisma.waitlists.findUnique({
      where: { id: waitlistId },
    });

    if (!waitlist) {
      return NextResponse.json(
        { error: "Waitlist not found" },
        { status: 404 },
      );
    }

    // Check for duplicate signup (by email)
    const existingSignup = await prisma.waitlist_signups.findUnique({
      where: {
        waitlistId_email: {
          waitlistId,
          email: email.trim().toLowerCase(),
        },
      },
    });

    if (existingSignup) {
      return NextResponse.json(
        { error: "This email is already signed up for this waitlist" },
        { status: 409 },
      );
    }

    // Create signup
    const id = createId();
    const signup = await prisma.waitlist_signups.create({
      data: {
        id,
        waitlistId,
        userId: null, // Manually added, no linked user account
        name: name.trim(),
        email: email.trim().toLowerCase(),
        mobile: mobile.trim(),
        notes: notes?.trim() || null,
        addedBy: staffUser.id,
      },
    });

    return NextResponse.json({
      success: true,
      message: "User added to waitlist successfully",
      signup: {
        id: signup.id,
        name: signup.name,
        email: signup.email,
        mobile: signup.mobile,
        createdAt: signup.createdAt,
      },
    });
  } catch (error) {
    console.error("Failed to add user to waitlist:", error);
    return NextResponse.json(
      { error: "Failed to add user to waitlist" },
      { status: 500 },
    );
  }
}

/**
 * DELETE /api/staff/dashboard/waitlists/[id]/signups
 * Delete a signup by signupId in query param
 */
export async function DELETE(request: NextRequest, { params }: RouteParams) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id: waitlistId } = params;
    const { searchParams } = new URL(request.url);
    const signupId = searchParams.get("signupId");

    if (!signupId) {
      return NextResponse.json(
        { error: "signupId is required" },
        { status: 400 },
      );
    }

    // Convex branch
    if (getDataSource("leads") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        await convexMutation("bookings/mutations:deleteWaitlistEntry", {
          id: signupId as any,
        });

        return NextResponse.json({
          success: true,
          message: "Signup removed successfully",
        });
      } catch (convexError) {
        console.error(
          "Convex waitlist signup delete failed, falling back to Prisma:",
          convexError,
        );
        // Fall through to Prisma
      }
    }

    // Check signup exists and belongs to this waitlist
    const signup = await prisma.waitlist_signups.findFirst({
      where: { id: signupId, waitlistId },
    });

    if (!signup) {
      return NextResponse.json({ error: "Signup not found" }, { status: 404 });
    }

    // Delete signup
    await prisma.waitlist_signups.delete({
      where: { id: signupId },
    });

    return NextResponse.json({
      success: true,
      message: "Signup removed successfully",
    });
  } catch (error) {
    console.error("Failed to delete waitlist signup:", error);
    return NextResponse.json(
      { error: "Failed to delete signup" },
      { status: 500 },
    );
  }
}
