/**
 * Comprehensive Unit Tests for Company Info Page
 * Tests form validation, API integration, data persistence
 */

import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { useRouter, useSearchParams } from "next/navigation";
import CompanyInfoPage from "@/app/[lang]/signup/company-info/page";
import { signupStorage } from "@/lib/storage";
import { logger } from "@/lib/logger";

// Mock dependencies
jest.mock("@/lib/storage");
jest.mock("@/lib/logger");

// Create mock functions before jest.mock (hoisting issue)
const mockPush = jest.fn();
const mockGet = jest.fn();

jest.mock("next/navigation", () => ({
  useRouter: () => ({ push: mockPush }),
  useSearchParams: () => ({ get: mockGet }),
  usePathname: () => "/en/signup/company-info",
  useParams: () => ({ lang: "en" }),
  redirect: jest.fn(),
  notFound: jest.fn(),
}));

// Form validation/field structure changed - needs rewrite
describe.skip("CompanyInfoPage Component", () => {
  beforeEach(() => {
    jest.clearAllMocks();
    mockPush.mockClear();
    mockGet.mockClear();
    (signupStorage.get as jest.Mock).mockReturnValue({
      email: "test@example.com",
      plan: "tier2",
      verified: true,
    });

    // Mock fetch to return proper Promise
    global.fetch = jest.fn(() =>
      Promise.resolve({
        ok: true,
        status: 200,
        json: () => Promise.resolve({ csrfToken: "test-token" }),
        text: () => Promise.resolve(""),
      } as Response),
    ) as jest.Mock;
  });

  describe("Form Rendering", () => {
    it("should render all required form fields", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        expect(screen.getByLabelText(/Company Name/i)).toBeInTheDocument();
        expect(screen.getByLabelText(/Industry/i)).toBeInTheDocument();
        expect(screen.getByLabelText(/Company Size/i)).toBeInTheDocument();
        expect(
          screen.getByLabelText(/GCC Country/i) ||
            screen.getByLabelText(/Country/i),
        ).toBeInTheDocument();
        expect(screen.getByLabelText(/Phone Number/i)).toBeInTheDocument();
        expect(screen.getByLabelText(/Agent Count/i)).toBeInTheDocument();
      });
    });

    it("should show progress indicator at step 3", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        expect(screen.getByText(/Company Details/i)).toBeInTheDocument();
        expect(
          screen.getByText(/3/i) || screen.getByText(/Step 3/i),
        ).toBeInTheDocument();
      });
    });

    it("should load existing company info if available", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      (signupStorage.get as jest.Mock).mockReturnValue({
        email: "test@example.com",
        verified: true,
        companyInfo: {
          companyName: "Test Clinic",
          industry: "healthcare",
          companySize: "11-50",
          gccCountry: "uae",
          phoneNumber: "+971 50 123 4567",
          agentCount: "5",
          agentUseCase: "Booking",
          companyDescription: "Test description",
          services: ["appointments"],
        },
      });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        const nameInput = screen.getByLabelText(
          /Company Name/i,
        ) as HTMLInputElement;
        expect(nameInput.value).toBe("Test Clinic");
      });
    });
  });

  describe("Form Validation", () => {
    it("should validate required fields", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        const submitButton = screen.getByRole("button", { name: /Continue/i });
        fireEvent.click(submitButton);
      });

      await waitFor(() => {
        // Should show validation errors
        const errors = screen.getAllByText(/required/i);
        expect(errors.length).toBeGreaterThan(0);
      });
    });

    it("should validate phone number format", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        const phoneInput = screen.getByLabelText(/Phone Number/i);
        fireEvent.change(phoneInput, { target: { value: "123" } }); // Too short

        const submitButton = screen.getByRole("button", { name: /Continue/i });
        fireEvent.click(submitButton);
      });

      await waitFor(() => {
        expect(
          screen.getByText(/invalid.*phone|phone.*invalid/i),
        ).toBeInTheDocument();
      });
    });

    it("should accept valid phone numbers", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        const phoneInput = screen.getByLabelText(/Phone Number/i);

        // Test various valid formats
        const validNumbers = [
          "+971 50 123 4567",
          "+966 5X XXX XXXX",
          "0501234567",
          "+1 (555) 123-4567",
        ];

        validNumbers.forEach((number) => {
          fireEvent.change(phoneInput, { target: { value: number } });
          expect(phoneInput).toHaveValue(number);
        });
      });
    });
  });

  describe("Industry Selection", () => {
    it("should render all 23 industry options", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        const industrySelect = screen.getByLabelText(
          /Industry/i,
        ) as HTMLSelectElement;
        const options = industrySelect.querySelectorAll("option");

        // Should have 24 options (1 placeholder + 23 industries)
        expect(options.length).toBe(24);

        // Verify key industries
        expect(
          screen.getByRole("option", { name: /Healthcare/i }),
        ).toBeInTheDocument();
        expect(
          screen.getByRole("option", { name: /Beauty.*Wellness/i }),
        ).toBeInTheDocument();
        expect(
          screen.getByRole("option", { name: /Hotels/i }),
        ).toBeInTheDocument();
      });
    });
  });

  describe("Services Multi-Select", () => {
    it("should allow selecting multiple services", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        const checkboxes = screen.getAllByRole("checkbox");

        // Select first 3 services
        fireEvent.click(checkboxes[0]);
        fireEvent.click(checkboxes[1]);
        fireEvent.click(checkboxes[2]);

        // Check selected count is displayed
        expect(screen.getByText(/3.*service/i)).toBeInTheDocument();
      });
    });

    it("should allow deselecting services", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        const checkboxes = screen.getAllByRole("checkbox");

        // Select and deselect
        fireEvent.click(checkboxes[0]);
        expect(screen.getByText(/1.*service/i)).toBeInTheDocument();

        fireEvent.click(checkboxes[0]); // Deselect
        expect(
          screen.queryByText(/service.*selected/i),
        ).not.toBeInTheDocument();
      });
    });
  });

  describe("GCC Country Selection", () => {
    it("should show all 6 GCC countries", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        const countrySelect =
          screen.getByLabelText(/GCC Country/i) ||
          screen.getByLabelText(/Country/i);
        const options = countrySelect.querySelectorAll("option");

        // Should have 7 options (1 placeholder + 6 countries)
        expect(options.length).toBe(7);

        // Verify all GCC countries
        expect(
          screen.getByRole("option", { name: /Saudi Arabia/i }),
        ).toBeInTheDocument();
        expect(
          screen.getByRole("option", { name: /UAE/i }),
        ).toBeInTheDocument();
        expect(
          screen.getByRole("option", { name: /Qatar/i }),
        ).toBeInTheDocument();
        expect(
          screen.getByRole("option", { name: /Kuwait/i }),
        ).toBeInTheDocument();
        expect(
          screen.getByRole("option", { name: /Bahrain/i }),
        ).toBeInTheDocument();
        expect(
          screen.getByRole("option", { name: /Oman/i }),
        ).toBeInTheDocument();
      });
    });
  });

  describe("Form Submission", () => {
    it("should submit company info to API with all fields", async () => {
      (global.fetch as jest.Mock)
        .mockResolvedValueOnce({ json: async () => ({ csrfToken: "token" }) })
        .mockResolvedValueOnce({
          ok: true,
          json: async () => ({ success: true }),
        });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        fireEvent.change(screen.getByLabelText(/Company Name/i), {
          target: { value: "Test Clinic" },
        });
        fireEvent.change(screen.getByLabelText(/Industry/i), {
          target: { value: "healthcare" },
        });
        fireEvent.change(screen.getByLabelText(/Company Size/i), {
          target: { value: "11-50" },
        });
        fireEvent.change(
          screen.getByLabelText(/GCC Country/i) ||
            screen.getByLabelText(/Country/i),
          {
            target: { value: "uae" },
          },
        );
        fireEvent.change(screen.getByLabelText(/Phone Number/i), {
          target: { value: "+971 50 123 4567" },
        });
        fireEvent.change(screen.getByLabelText(/Agent Count/i), {
          target: { value: "5" },
        });

        const submitButton = screen.getByRole("button", { name: /Continue/i });
        fireEvent.click(submitButton);
      });

      await waitFor(() => {
        expect(global.fetch).toHaveBeenCalledWith(
          "/api/onboarding/company-info",
          expect.objectContaining({
            method: "POST",
            headers: expect.objectContaining({
              "x-csrf-token": "token",
            }),
            body: expect.stringContaining("Test Clinic"),
          }),
        );
      });
    });

    it("should save company info to localStorage", async () => {
      (global.fetch as jest.Mock)
        .mockResolvedValueOnce({ json: async () => ({ csrfToken: "token" }) })
        .mockResolvedValueOnce({
          ok: true,
          json: async () => ({ success: true }),
        });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        fireEvent.change(screen.getByLabelText(/Company Name/i), {
          target: { value: "Test Clinic" },
        });
        fireEvent.change(screen.getByLabelText(/Industry/i), {
          target: { value: "healthcare" },
        });
        fireEvent.change(screen.getByLabelText(/Company Size/i), {
          target: { value: "11-50" },
        });
        fireEvent.change(
          screen.getByLabelText(/GCC Country/i) ||
            screen.getByLabelText(/Country/i),
          {
            target: { value: "uae" },
          },
        );
        fireEvent.change(screen.getByLabelText(/Phone Number/i), {
          target: { value: "+971 50 123 4567" },
        });
        fireEvent.change(screen.getByLabelText(/Agent Count/i), {
          target: { value: "5" },
        });

        fireEvent.click(screen.getByRole("button", { name: /Continue/i }));
      });

      await waitFor(() => {
        expect(signupStorage.saveCompanyInfo).toHaveBeenCalledWith(
          expect.objectContaining({
            companyName: "Test Clinic",
            industry: "healthcare",
            companySize: "11-50",
          }),
        );
      });
    });

    it("should redirect to onboarding on success", async () => {
      (global.fetch as jest.Mock)
        .mockResolvedValueOnce({ json: async () => ({ csrfToken: "token" }) })
        .mockResolvedValueOnce({
          ok: true,
          json: async () => ({ success: true }),
        });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        // Fill all required fields
        fireEvent.change(screen.getByLabelText(/Company Name/i), {
          target: { value: "Test Clinic" },
        });
        fireEvent.change(screen.getByLabelText(/Industry/i), {
          target: { value: "healthcare" },
        });
        fireEvent.change(screen.getByLabelText(/Company Size/i), {
          target: { value: "11-50" },
        });
        fireEvent.change(
          screen.getByLabelText(/GCC Country/i) ||
            screen.getByLabelText(/Country/i),
          {
            target: { value: "uae" },
          },
        );
        fireEvent.change(screen.getByLabelText(/Phone Number/i), {
          target: { value: "+971 50 123 4567" },
        });
        fireEvent.change(screen.getByLabelText(/Agent Count/i), {
          target: { value: "5" },
        });

        fireEvent.click(screen.getByRole("button", { name: /Continue/i }));
      });

      await waitFor(() => {
        expect(mockPush).toHaveBeenCalledWith("/en/signup/onboarding");
      });
    });

    it("should handle API errors gracefully", async () => {
      (global.fetch as jest.Mock)
        .mockResolvedValueOnce({ json: async () => ({ csrfToken: "token" }) })
        .mockResolvedValueOnce({
          ok: false,
          json: async () => ({ error: "Failed to save company info" }),
        });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        // Fill required fields
        fireEvent.change(screen.getByLabelText(/Company Name/i), {
          target: { value: "Test Clinic" },
        });
        fireEvent.change(screen.getByLabelText(/Industry/i), {
          target: { value: "healthcare" },
        });
        fireEvent.change(screen.getByLabelText(/Company Size/i), {
          target: { value: "11-50" },
        });
        fireEvent.change(
          screen.getByLabelText(/GCC Country/i) ||
            screen.getByLabelText(/Country/i),
          {
            target: { value: "uae" },
          },
        );
        fireEvent.change(screen.getByLabelText(/Phone Number/i), {
          target: { value: "+971 50 123 4567" },
        });
        fireEvent.change(screen.getByLabelText(/Agent Count/i), {
          target: { value: "5" },
        });

        fireEvent.click(screen.getByRole("button", { name: /Continue/i }));
      });

      await waitFor(() => {
        expect(
          screen.getByText(/Failed to save company info/i),
        ).toBeInTheDocument();
      });
    });
  });

  describe("Skip Functionality", () => {
    it("should allow skipping company info", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        const skipButton = screen.getByRole("button", { name: /Skip/i });
        fireEvent.click(skipButton);
      });

      expect(mockPush).toHaveBeenCalledWith("/en/signup/onboarding");
    });

    it("should skip without calling API", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        const skipButton = screen.getByRole("button", { name: /Skip/i });
        fireEvent.click(skipButton);
      });

      // Should only have called CSRF endpoint, not company-info endpoint
      expect(global.fetch).toHaveBeenCalledTimes(1);
      expect(global.fetch).toHaveBeenCalledWith("/api/csrf");
    });
  });

  describe("CSRF Protection", () => {
    it("should fetch CSRF token on mount", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        expect(global.fetch).toHaveBeenCalledWith("/api/csrf");
      });
    });

    it("should show error if CSRF token is missing", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "" }),
      });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        // Fill all fields
        fireEvent.change(screen.getByLabelText(/Company Name/i), {
          target: { value: "Test Clinic" },
        });
        fireEvent.change(screen.getByLabelText(/Industry/i), {
          target: { value: "healthcare" },
        });
        fireEvent.change(screen.getByLabelText(/Company Size/i), {
          target: { value: "11-50" },
        });
        fireEvent.change(
          screen.getByLabelText(/GCC Country/i) ||
            screen.getByLabelText(/Country/i),
          {
            target: { value: "uae" },
          },
        );
        fireEvent.change(screen.getByLabelText(/Phone Number/i), {
          target: { value: "+971 50 123 4567" },
        });
        fireEvent.change(screen.getByLabelText(/Agent Count/i), {
          target: { value: "5" },
        });

        fireEvent.click(screen.getByRole("button", { name: /Continue/i }));
      });

      await waitFor(() => {
        expect(screen.getByText(/security error/i)).toBeInTheDocument();
      });
    });
  });

  describe("Stripe Session Context", () => {
    it("should pass stripe session ID to API if present", async () => {
      mockGet.mockImplementation((key: string) => {
        if (key === "session_id") return "sess_123";
        return null;
      });

      (global.fetch as jest.Mock)
        .mockResolvedValueOnce({ json: async () => ({ csrfToken: "token" }) })
        .mockResolvedValueOnce({
          ok: true,
          json: async () => ({ success: true }),
        });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        // Fill required fields
        fireEvent.change(screen.getByLabelText(/Company Name/i), {
          target: { value: "Test Clinic" },
        });
        fireEvent.change(screen.getByLabelText(/Industry/i), {
          target: { value: "healthcare" },
        });
        fireEvent.change(screen.getByLabelText(/Company Size/i), {
          target: { value: "11-50" },
        });
        fireEvent.change(
          screen.getByLabelText(/GCC Country/i) ||
            screen.getByLabelText(/Country/i),
          {
            target: { value: "uae" },
          },
        );
        fireEvent.change(screen.getByLabelText(/Phone Number/i), {
          target: { value: "+971 50 123 4567" },
        });
        fireEvent.change(screen.getByLabelText(/Agent Count/i), {
          target: { value: "5" },
        });

        fireEvent.click(screen.getByRole("button", { name: /Continue/i }));
      });

      await waitFor(() => {
        expect(global.fetch).toHaveBeenCalledWith(
          "/api/onboarding/company-info",
          expect.objectContaining({
            body: expect.stringContaining("sess_123"),
          }),
        );
      });
    });
  });

  describe("Plan Context Passing", () => {
    it("should send selected plan to API", async () => {
      (signupStorage.get as jest.Mock).mockReturnValue({
        email: "test@example.com",
        plan: { tierId: "tier3", billingPeriod: "yearly", currency: "SAR" },
        verified: true,
      });

      (global.fetch as jest.Mock)
        .mockResolvedValueOnce({ json: async () => ({ csrfToken: "token" }) })
        .mockResolvedValueOnce({
          ok: true,
          json: async () => ({ success: true }),
        });

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        // Fill required fields
        fireEvent.change(screen.getByLabelText(/Company Name/i), {
          target: { value: "Test Clinic" },
        });
        fireEvent.change(screen.getByLabelText(/Industry/i), {
          target: { value: "healthcare" },
        });
        fireEvent.change(screen.getByLabelText(/Company Size/i), {
          target: { value: "11-50" },
        });
        fireEvent.change(
          screen.getByLabelText(/GCC Country/i) ||
            screen.getByLabelText(/Country/i),
          {
            target: { value: "uae" },
          },
        );
        fireEvent.change(screen.getByLabelText(/Phone Number/i), {
          target: { value: "+971 50 123 4567" },
        });
        fireEvent.change(screen.getByLabelText(/Agent Count/i), {
          target: { value: "5" },
        });

        fireEvent.click(screen.getByRole("button", { name: /Continue/i }));
      });

      await waitFor(() => {
        const call = (global.fetch as jest.Mock).mock.calls.find(
          (call) => call[0] === "/api/onboarding/company-info",
        );
        const body = JSON.parse(call[1].body);

        expect(body.selectedPlan).toBe("tier3");
        expect(body.billingPeriod).toBe("yearly");
        expect(body.currency).toBe("SAR");
      });
    });
  });

  describe("Loading States", () => {
    it("should disable submit button while submitting", async () => {
      (global.fetch as jest.Mock)
        .mockResolvedValueOnce({ json: async () => ({ csrfToken: "token" }) })
        .mockImplementation(
          () => new Promise((resolve) => setTimeout(resolve, 1000)),
        );

      render(<CompanyInfoPage params={{ lang: "en" }} />);

      await waitFor(() => {
        // Fill required fields
        fireEvent.change(screen.getByLabelText(/Company Name/i), {
          target: { value: "Test Clinic" },
        });
        fireEvent.change(screen.getByLabelText(/Industry/i), {
          target: { value: "healthcare" },
        });
        fireEvent.change(screen.getByLabelText(/Company Size/i), {
          target: { value: "11-50" },
        });
        fireEvent.change(
          screen.getByLabelText(/GCC Country/i) ||
            screen.getByLabelText(/Country/i),
          {
            target: { value: "uae" },
          },
        );
        fireEvent.change(screen.getByLabelText(/Phone Number/i), {
          target: { value: "+971 50 123 4567" },
        });
        fireEvent.change(screen.getByLabelText(/Agent Count/i), {
          target: { value: "5" },
        });

        const submitButton = screen.getByRole("button", { name: /Continue/i });
        fireEvent.click(submitButton);

        // Should be disabled
        expect(submitButton).toBeDisabled();
        expect(screen.getByText(/Saving.../i)).toBeInTheDocument();
      });
    });
  });

  describe("Arabic Language Support", () => {
    it("should render in Arabic with RTL", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      render(<CompanyInfoPage params={{ lang: "ar" }} />);

      await waitFor(() => {
        expect(screen.getByText(/معلومات الشركة/i)).toBeInTheDocument();

        const form = document.querySelector("form");
        expect(form).toHaveAttribute("dir", "rtl");
      });
    });

    it("should show Arabic validation errors", async () => {
      (global.fetch as jest.Mock).mockResolvedValueOnce({
        json: async () => ({ csrfToken: "token" }),
      });

      render(<CompanyInfoPage params={{ lang: "ar" }} />);

      await waitFor(() => {
        fireEvent.click(screen.getByRole("button", { name: /متابعة/i }));
      });

      await waitFor(() => {
        expect(screen.getByText(/مطلوب|يجب/i)).toBeInTheDocument();
      });
    });
  });
});
