/**
 * User Links Tab Component Tests
 * Tests for the Links tab in UserModal component
 */

import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";

// Mock data
const mockUserLinks = [
  {
    id: "link-1",
    linkType: "KNOWLEDGE_BASE" as const,
    title: "Customer Knowledge Base",
    url: "https://kb.example.com/customer-123",
    description: "Knowledge base portal for the customer",
    icon: null,
    isActive: true,
    sortOrder: 1,
    createdAt: "2024-01-15T10:00:00Z",
  },
  {
    id: "link-2",
    linkType: "AI_AGENT" as const,
    title: "AI Agent Dashboard",
    url: "https://agent.example.com/dashboard",
    description: null,
    icon: null,
    isActive: true,
    sortOrder: 2,
    createdAt: "2024-01-16T10:00:00Z",
  },
];

const LINK_TYPE_OPTIONS = [
  { value: "KNOWLEDGE_BASE", label: "Knowledge Base", icon: "📚" },
  { value: "AI_AGENT", label: "AI Agent", icon: "🤖" },
  { value: "AI_VOICE_AGENT", label: "AI Voice Agent", icon: "🎙️" },
  { value: "WHATSAPP_INTEGRATION", label: "WhatsApp", icon: "💬" },
  { value: "APPOINTMENTS", label: "Appointments", icon: "📅" },
  { value: "CUSTOMERS", label: "Customers", icon: "👥" },
  { value: "WAITLISTS", label: "Waitlists", icon: "⏳" },
  { value: "CALENDAR", label: "Calendar", icon: "🗓️" },
  { value: "ANALYTICS", label: "Analytics", icon: "📈" },
  { value: "REPORTS", label: "Reports", icon: "📋" },
  { value: "BILLING", label: "Billing", icon: "💳" },
  { value: "DASHBOARD", label: "Dashboard", icon: "📊" },
  { value: "DOCUMENTATION", label: "Documentation", icon: "📄" },
  { value: "SETTINGS", label: "Settings", icon: "⚙️" },
  { value: "SUPPORT", label: "Support", icon: "🆘" },
  { value: "CUSTOM", label: "Custom", icon: "🔗" },
];

describe("Link Type Options", () => {
  it("should have all required link types", () => {
    const requiredTypes = [
      "KNOWLEDGE_BASE",
      "AI_AGENT",
      "AI_VOICE_AGENT",
      "WHATSAPP_INTEGRATION",
      "CUSTOM",
    ];

    requiredTypes.forEach((type) => {
      const option = LINK_TYPE_OPTIONS.find((opt) => opt.value === type);
      expect(option).toBeDefined();
      expect(option?.label).toBeTruthy();
      expect(option?.icon).toBeTruthy();
    });
  });

  it("should have unique values for all link types", () => {
    const values = LINK_TYPE_OPTIONS.map((opt) => opt.value);
    const uniqueValues = new Set(values);
    expect(uniqueValues.size).toBe(values.length);
  });

  it("should have icons for all link types", () => {
    LINK_TYPE_OPTIONS.forEach((option) => {
      expect(option.icon).toBeTruthy();
      expect(option.icon.length).toBeGreaterThan(0);
    });
  });
});

describe("User Links Data Structure", () => {
  it("should have required fields in link objects", () => {
    mockUserLinks.forEach((link) => {
      expect(link.id).toBeDefined();
      expect(link.linkType).toBeDefined();
      expect(link.title).toBeDefined();
      expect(link.url).toBeDefined();
      expect(link.isActive).toBeDefined();
      expect(link.sortOrder).toBeDefined();
      expect(link.createdAt).toBeDefined();
    });
  });

  it("should have valid URLs", () => {
    mockUserLinks.forEach((link) => {
      expect(() => new URL(link.url)).not.toThrow();
    });
  });

  it("should sort links by sortOrder", () => {
    const sorted = [...mockUserLinks].sort((a, b) => a.sortOrder - b.sortOrder);
    expect(sorted[0].sortOrder).toBeLessThanOrEqual(sorted[1].sortOrder);
  });
});

describe("Link Form Validation", () => {
  it("should require title", () => {
    const formData = {
      linkType: "CUSTOM",
      title: "",
      url: "https://example.com",
      description: "",
    };

    const isValid = formData.title.trim() !== "" && formData.url.trim() !== "";
    expect(isValid).toBe(false);
  });

  it("should require URL", () => {
    const formData = {
      linkType: "CUSTOM",
      title: "Test Link",
      url: "",
      description: "",
    };

    const isValid = formData.title.trim() !== "" && formData.url.trim() !== "";
    expect(isValid).toBe(false);
  });

  it("should allow empty description", () => {
    const formData = {
      linkType: "CUSTOM",
      title: "Test Link",
      url: "https://example.com",
      description: "",
    };

    const isValid = formData.title.trim() !== "" && formData.url.trim() !== "";
    expect(isValid).toBe(true);
  });

  it("should validate URL format", () => {
    const validUrls = [
      "https://example.com",
      "https://sub.domain.com/path",
      "http://localhost:3000",
      "https://example.com/path?query=value",
    ];

    const invalidUrls = [
      "not-a-url",
      "ftp://invalid",
      "mailto:test@example.com",
    ];

    validUrls.forEach((url) => {
      let isValid = true;
      try {
        new URL(url);
      } catch {
        isValid = false;
      }
      expect(isValid).toBe(true);
    });

    invalidUrls.forEach((url) => {
      let isValid = true;
      try {
        const parsed = new URL(url);
        isValid = parsed.protocol === "https:" || parsed.protocol === "http:";
      } catch {
        isValid = false;
      }
      expect(isValid).toBe(false);
    });
  });
});

describe("Link Display Logic", () => {
  it("should truncate long URLs for display", () => {
    const longUrl =
      "https://example.com/very/long/path/that/exceeds/fifty/characters/in/length/and/continues";
    const maxLength = 50;
    const displayUrl =
      longUrl.length > maxLength
        ? longUrl.substring(0, maxLength) + "..."
        : longUrl;

    expect(displayUrl.length).toBeLessThanOrEqual(maxLength + 3);
  });

  it("should not truncate short URLs", () => {
    const shortUrl = "https://example.com";
    const maxLength = 50;
    const displayUrl =
      shortUrl.length > maxLength
        ? shortUrl.substring(0, maxLength) + "..."
        : shortUrl;

    expect(displayUrl).toBe(shortUrl);
    expect(displayUrl.endsWith("...")).toBe(false);
  });

  it("should get correct icon for link type", () => {
    const getLinkTypeInfo = (type: string) => {
      return (
        LINK_TYPE_OPTIONS.find((opt) => opt.value === type) || {
          value: type,
          label: type,
          icon: "🔗",
        }
      );
    };

    expect(getLinkTypeInfo("KNOWLEDGE_BASE").icon).toBe("📚");
    expect(getLinkTypeInfo("AI_AGENT").icon).toBe("🤖");
    expect(getLinkTypeInfo("UNKNOWN_TYPE").icon).toBe("🔗");
  });

  it("should filter active links only when needed", () => {
    const links = [
      { id: "1", isActive: true },
      { id: "2", isActive: false },
      { id: "3", isActive: true },
    ];

    const activeLinks = links.filter((l) => l.isActive);
    expect(activeLinks.length).toBe(2);
  });
});

describe("Link CRUD Operations", () => {
  it("should prepare correct payload for creating a link", () => {
    const formData = {
      linkType: "AI_AGENT",
      title: "Test Agent",
      url: "https://agent.example.com",
      description: "Test description",
    };

    const payload = {
      linkType: formData.linkType,
      title: formData.title,
      url: formData.url,
      description: formData.description || null,
    };

    expect(payload.linkType).toBe("AI_AGENT");
    expect(payload.title).toBe("Test Agent");
    expect(payload.url).toBe("https://agent.example.com");
    expect(payload.description).toBe("Test description");
  });

  it("should prepare correct payload for updating a link", () => {
    const existingLink = mockUserLinks[0];
    const updates = {
      title: "Updated Title",
      url: "https://new-url.example.com",
    };

    const payload = {
      ...updates,
    };

    expect(payload.title).toBe("Updated Title");
    expect(payload.url).toBe("https://new-url.example.com");
  });

  it("should handle null description correctly", () => {
    const formData = {
      linkType: "CUSTOM",
      title: "Test",
      url: "https://example.com",
      description: "",
    };

    const payload = {
      ...formData,
      description: formData.description || null,
    };

    expect(payload.description).toBeNull();
  });
});

describe("Link State Management", () => {
  it("should reset form after successful save", () => {
    const initialState = {
      linkType: "CUSTOM" as const,
      title: "",
      url: "",
      description: "",
    };

    const filledState = {
      linkType: "AI_AGENT" as const,
      title: "Test",
      url: "https://example.com",
      description: "Desc",
    };

    // Simulate reset
    const resetForm = () => initialState;
    const result = resetForm();

    expect(result.linkType).toBe("CUSTOM");
    expect(result.title).toBe("");
    expect(result.url).toBe("");
    expect(result.description).toBe("");
  });

  it("should populate form when editing a link", () => {
    const linkToEdit = mockUserLinks[0];

    const formState = {
      linkType: linkToEdit.linkType,
      title: linkToEdit.title,
      url: linkToEdit.url,
      description: linkToEdit.description || "",
    };

    expect(formState.linkType).toBe("KNOWLEDGE_BASE");
    expect(formState.title).toBe("Customer Knowledge Base");
    expect(formState.url).toBe("https://kb.example.com/customer-123");
    expect(formState.description).toBe(
      "Knowledge base portal for the customer",
    );
  });
});
