import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth";
import {
  scheduleNoShowReminders,
  schedulePostTreatmentReminders,
  scheduleRescheduleFollowup,
} from "@/lib/reminders";
import { requestFeedback } from "@/lib/chatbot";
import { triggerTree } from "@/lib/tree-trigger";

export async function PUT(
  req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;

  let body: { status?: string };
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }

  const { status } = body;
  if (!status) {
    return NextResponse.json({ error: "Status is required" }, { status: 400 });
  }

  const validStatuses = ["scheduled", "confirmed", "arrived", "in_progress", "completed", "no_show", "cancelled", "rescheduled"];
  if (!validStatuses.includes(status)) {
    return NextResponse.json({ error: `Invalid status: ${status}` }, { status: 400 });
  }

  const existing = await prisma.appointment.findFirst({
    where: { id, clinicId: session.id },
  });
  if (!existing) {
    return NextResponse.json({ error: "Appointment not found" }, { status: 404 });
  }

  // Build update data
  const updateData: Record<string, unknown> = { status };
  if (status === "confirmed") updateData.confirmedAt = new Date();
  if (status === "arrived") updateData.arrivedAt = new Date();
  if (status === "completed") updateData.completedAt = new Date();

  const appointment = await prisma.appointment.update({
    where: { id },
    data: updateData,
    include: { lead: true, treatment: true },
  });

  // Update lead status
  const leadStatusMap: Record<string, string> = {
    confirmed: "confirmed",
    arrived: "arrived",
    completed: "completed",
    no_show: "no_show",
    cancelled: "cancelled",
  };

  if (leadStatusMap[status]) {
    try {
      await prisma.lead.update({
        where: { id: appointment.leadId },
        data: { status: leadStatusMap[status] },
      });
    } catch (err) {
      console.error(`⚠️ Failed to update lead status:`, err);
    }
  }

  // Cancel pending reminders on terminal/arrived states
  if (["cancelled", "completed", "arrived"].includes(status)) {
    try {
      await prisma.scheduledReminder.updateMany({
        where: { appointmentId: id, status: "pending" },
        data: { status: "skipped" },
      });
    } catch (err) {
      console.error(`⚠️ Failed to skip reminders:`, err);
    }
  }

  // Upgrade #8: On reschedule, skip pre-appointment but schedule follow-up
  if (status === "rescheduled") {
    try {
      // Skip all pre-appointment reminders
      await prisma.scheduledReminder.updateMany({
        where: {
          appointmentId: id,
          status: "pending",
          template: {
            trigger: { notIn: ["reschedule_followup"] },
          },
        },
        data: { status: "skipped" },
      });

      // Schedule 48-hour follow-up to check if they rebooked
      await scheduleRescheduleFollowup(id);
    } catch (err) {
      console.error(`⚠️ Failed to handle reschedule reminders:`, err);
    }
  }

  // ── No-show: legacy reminders + tree ──
  if (status === "no_show") {
    scheduleNoShowReminders(id).catch(err =>
      console.error(`⚠️ scheduleNoShowReminders failed:`, err)
    );
    // Pause any active booking journey, then start no-show tree
    prisma.userJourney.updateMany({
      where: { appointmentId: id, status: "active" },
      data: { status: "paused" },
    }).then(() =>
      triggerTree(id, "no_show").then(r =>
        console.log(`🌳 No-show tree: ${r.started ? r.treeName : r.error}`)
      )
    ).catch(err => console.error("⚠️ No-show tree failed:", err));
  }

  // ── Completed: legacy reminders + tree + feedback ──
  if (status === "completed") {
    schedulePostTreatmentReminders(id).catch(err =>
      console.error(`⚠️ schedulePostTreatmentReminders failed:`, err)
    );
    requestFeedback(
      session.id,
      appointment.lead.phone,
      appointment.lead.name.split(" ")[0],
      appointment.treatment.name
    ).catch(err => console.error(`⚠️ requestFeedback failed:`, err));

    // Pause active booking journey, start completed tree
    prisma.userJourney.updateMany({
      where: { appointmentId: id, status: "active" },
      data: { status: "completed" },
    }).then(() =>
      triggerTree(id, "completed").then(r =>
        console.log(`🌳 Completed tree: ${r.started ? r.treeName : r.error}`)
      )
    ).catch(err => console.error("⚠️ Completed tree failed:", err));
  }

  return NextResponse.json(appointment);
}
