import { render, screen, fireEvent } from "@testing-library/react";
import AppointmentDetailModal from "@/app/[lang]/dashboard/components/AppointmentDetailModal";
import type { BookingDetail } from "@/app/[lang]/dashboard/components/AppointmentDetailModal";

// Mock CSRF client
jest.mock("@/lib/csrf-client", () => ({
  fetchWithCSRF: jest.fn(),
}));

// ---- helpers ---------------------------------------------------------------

const baseBooking: BookingDetail = {
  id: "bk-001",
  customerName: "Fatima Al-Thani",
  customerPhone: "+974 5555 9999",
  customerEmail: "fatima@example.com",
  service: "Hair Treatment",
  appointmentDate: "2026-03-15",
  appointmentTime: "09:30",
  duration: 45,
  status: "pending",
  source: "whatsapp",
  notes: "Prefers organic products",
  depositAmount: 100,
  depositPaid: true,
  totalAmount: 250,
  createdAt: "2026-03-10",
};

// ---- tests -----------------------------------------------------------------

describe("AppointmentDetailModal", () => {
  const onClose = jest.fn();
  const onStatusChange = jest.fn();

  beforeEach(() => {
    jest.clearAllMocks();
  });

  afterEach(() => {
    jest.restoreAllMocks();
  });

  // ---------- basic rendering -----------------------------------------------

  describe("rendering", () => {
    it("displays the service name in the header", () => {
      render(
        <AppointmentDetailModal
          booking={baseBooking}
          lang="en"
          onClose={onClose}
        />,
      );

      expect(screen.getByText("Hair Treatment")).toBeInTheDocument();
    });

    it("displays the customer name", () => {
      render(
        <AppointmentDetailModal
          booking={baseBooking}
          lang="en"
          onClose={onClose}
        />,
      );

      expect(screen.getByText("Fatima Al-Thani")).toBeInTheDocument();
    });

    it("displays the customer phone", () => {
      render(
        <AppointmentDetailModal
          booking={baseBooking}
          lang="en"
          onClose={onClose}
        />,
      );

      expect(screen.getByText("+974 5555 9999")).toBeInTheDocument();
    });

    it("displays the customer email", () => {
      render(
        <AppointmentDetailModal
          booking={baseBooking}
          lang="en"
          onClose={onClose}
        />,
      );

      expect(screen.getByText("fatima@example.com")).toBeInTheDocument();
    });

    it("displays notes when present", () => {
      render(
        <AppointmentDetailModal
          booking={baseBooking}
          lang="en"
          onClose={onClose}
        />,
      );

      expect(screen.getByText("Prefers organic products")).toBeInTheDocument();
    });

    it("displays the source label", () => {
      render(
        <AppointmentDetailModal
          booking={baseBooking}
          lang="en"
          onClose={onClose}
        />,
      );

      expect(screen.getByText("WhatsApp")).toBeInTheDocument();
    });
  });

  // ---------- status badges -------------------------------------------------

  describe("status badge", () => {
    it("shows Pending for pending status", () => {
      render(
        <AppointmentDetailModal
          booking={{ ...baseBooking, status: "pending" }}
          lang="en"
          onClose={onClose}
        />,
      );

      expect(screen.getByText("Pending")).toBeInTheDocument();
    });

    it("shows Confirmed for confirmed status", () => {
      render(
        <AppointmentDetailModal
          booking={{ ...baseBooking, status: "confirmed" }}
          lang="en"
          onClose={onClose}
        />,
      );

      expect(screen.getByText("Confirmed")).toBeInTheDocument();
    });

    it("shows Completed for completed status", () => {
      render(
        <AppointmentDetailModal
          booking={{ ...baseBooking, status: "completed" }}
          lang="en"
          onClose={onClose}
        />,
      );

      expect(screen.getByText("Completed")).toBeInTheDocument();
    });

    it("shows Cancelled for cancelled status", () => {
      render(
        <AppointmentDetailModal
          booking={{ ...baseBooking, status: "cancelled" }}
          lang="en"
          onClose={onClose}
        />,
      );

      expect(screen.getByText("Cancelled")).toBeInTheDocument();
    });
  });

  // ---------- close button --------------------------------------------------

  describe("close button", () => {
    it("calls onClose when footer Cancel button is clicked", () => {
      render(
        <AppointmentDetailModal
          booking={baseBooking}
          lang="en"
          onClose={onClose}
        />,
      );

      // dt.cancelAction is "Cancel"
      const closeBtn = screen.getByText("Cancel");
      fireEvent.click(closeBtn);

      expect(onClose).toHaveBeenCalledTimes(1);
    });

    it("calls onClose when backdrop is clicked", () => {
      const { container } = render(
        <AppointmentDetailModal
          booking={baseBooking}
          lang="en"
          onClose={onClose}
        />,
      );

      // Click the outer fixed overlay div
      const backdrop = container.querySelector(".fixed.inset-0");
      if (backdrop) {
        fireEvent.click(backdrop);
      }

      expect(onClose).toHaveBeenCalled();
    });
  });

  // ---------- confirm button ------------------------------------------------

  describe("confirm action", () => {
    it("shows Confirmed button for pending bookings when onStatusChange is provided", () => {
      render(
        <AppointmentDetailModal
          booking={{ ...baseBooking, status: "pending" }}
          lang="en"
          onClose={onClose}
          onStatusChange={onStatusChange}
        />,
      );

      // dt.statusConfirmed is "Confirmed"
      // The status badge also says "Pending", but the action button says "Confirmed"
      const confirmBtns = screen.getAllByText("Confirmed");
      // At least one should be a button (the action button)
      expect(confirmBtns.length).toBeGreaterThanOrEqual(1);
    });

    it("does not show Confirmed action button for non-pending bookings", () => {
      render(
        <AppointmentDetailModal
          booking={{ ...baseBooking, status: "completed" }}
          lang="en"
          onClose={onClose}
          onStatusChange={onStatusChange}
        />,
      );

      // "Completed" appears as status badge, but there should be no "Confirmed" action button
      // For completed bookings the confirm button is not shown
      const confirmBtns = screen.queryAllByText("Confirmed");
      // If "Confirmed" appears, it should not be as an action button
      confirmBtns.forEach((el) => {
        expect(el.tagName).not.toBe("BUTTON");
      });
    });

    it("calls onStatusChange with confirmed when Confirmed button is clicked", () => {
      render(
        <AppointmentDetailModal
          booking={{ ...baseBooking, status: "pending" }}
          lang="en"
          onClose={onClose}
          onStatusChange={onStatusChange}
        />,
      );

      // Find the Confirmed button (not the status badge)
      const confirmBtns = screen.getAllByText("Confirmed");
      const actionBtn = confirmBtns.find(
        (el) => el.closest("button") && el.closest(".px-6"),
      );
      if (actionBtn) {
        fireEvent.click(actionBtn.closest("button")!);
      } else {
        // Fall back to clicking any "Confirmed" button
        fireEvent.click(confirmBtns[confirmBtns.length - 1].closest("button")!);
      }

      expect(onStatusChange).toHaveBeenCalledWith("bk-001", "confirmed");
    });
  });

  // ---------- reschedule ----------------------------------------------------

  describe("reschedule", () => {
    it("shows Reschedule button for pending bookings", () => {
      render(
        <AppointmentDetailModal
          booking={{ ...baseBooking, status: "pending" }}
          lang="en"
          onClose={onClose}
        />,
      );

      expect(screen.getByText("Reschedule")).toBeInTheDocument();
    });

    it("does not show Reschedule button for completed bookings", () => {
      render(
        <AppointmentDetailModal
          booking={{ ...baseBooking, status: "completed" }}
          lang="en"
          onClose={onClose}
        />,
      );

      expect(screen.queryByText("Reschedule")).not.toBeInTheDocument();
    });
  });

  // ---------- payment info --------------------------------------------------

  describe("payment information", () => {
    it("shows deposit paid badge when deposit is paid", () => {
      render(
        <AppointmentDetailModal
          booking={{ ...baseBooking, depositPaid: true }}
          lang="en"
          onClose={onClose}
        />,
      );

      // Deposit Paid badge appears in header
      const badges = screen.getAllByText(/Deposit Paid/);
      expect(badges.length).toBeGreaterThan(0);
    });

    it("shows total amount when available", () => {
      render(
        <AppointmentDetailModal
          booking={{ ...baseBooking, totalAmount: 250 }}
          lang="en"
          onClose={onClose}
        />,
      );

      expect(screen.getByText("QAR 250.00")).toBeInTheDocument();
    });
  });
});
