/**
 * WorkflowCard Component Tests
 * Tests for the reusable workflow card component
 */

import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import "@testing-library/jest-dom";
import WorkflowCard from "@/components/dashboard/workflow/WorkflowCard";
import { MessageSquare, Users } from "lucide-react";

describe("WorkflowCard Component", () => {
  const defaultProps = {
    title: "WhatsApp Automation",
    description: "Automated responses for WhatsApp messages",
    status: "active" as const,
  };

  describe("Basic Rendering", () => {
    it("should render with title and description", () => {
      render(<WorkflowCard {...defaultProps} />);

      expect(screen.getByText("WhatsApp Automation")).toBeInTheDocument();
      expect(
        screen.getByText("Automated responses for WhatsApp messages"),
      ).toBeInTheDocument();
    });

    it("should render with custom icon", () => {
      const { container } = render(
        <WorkflowCard
          {...defaultProps}
          icon={<MessageSquare data-testid="custom-icon" />}
        />,
      );

      expect(screen.getByTestId("custom-icon")).toBeInTheDocument();
    });

    it("should render without icon", () => {
      const { container } = render(<WorkflowCard {...defaultProps} />);

      // Should not have icon container if no icon provided
      const iconContainer = container.querySelector(
        ".rounded-lg.bg-slate-50.p-3",
      );
      expect(iconContainer).not.toBeInTheDocument();
    });
  });

  describe("Status Badges", () => {
    it("should display active status badge", () => {
      render(<WorkflowCard {...defaultProps} status="active" />);

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

    it("should display inactive status badge", () => {
      render(<WorkflowCard {...defaultProps} status="inactive" />);

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

    it("should display error status badge", () => {
      render(<WorkflowCard {...defaultProps} status="error" />);

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

    it("should display locked status badge", () => {
      render(<WorkflowCard {...defaultProps} status="locked" />);

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

    it("should apply correct CSS classes for active status", () => {
      const { container } = render(
        <WorkflowCard {...defaultProps} status="active" />,
      );

      const badge = screen.getByText("Active").parentElement;
      expect(badge).toHaveClass("bg-emerald-100", "text-emerald-700");
    });

    it("should apply correct CSS classes for error status", () => {
      const { container } = render(
        <WorkflowCard {...defaultProps} status="error" />,
      );

      const badge = screen.getByText("Error").parentElement;
      expect(badge).toHaveClass("bg-red-100", "text-red-700");
    });
  });

  describe("Locked State", () => {
    it("should show locked overlay when locked=true", () => {
      render(<WorkflowCard {...defaultProps} locked={true} />);

      expect(screen.getByText("Feature Locked")).toBeInTheDocument();
      expect(
        screen.getByText(/This feature is not available on your current plan/i),
      ).toBeInTheDocument();
    });

    it("should show upgrade message when requiresUpgrade=true", () => {
      render(
        <WorkflowCard
          {...defaultProps}
          locked={true}
          requiresUpgrade={true}
          upgradeTier="Professional"
        />,
      );

      expect(
        screen.getByText(/Upgrade to Professional to unlock this feature/i),
      ).toBeInTheDocument();
    });

    it("should show upgrade button when requiresUpgrade=true", () => {
      render(
        <WorkflowCard
          {...defaultProps}
          locked={true}
          requiresUpgrade={true}
          upgradeTier="Professional"
        />,
      );

      expect(screen.getByText("Upgrade Now")).toBeInTheDocument();
    });

    it("should not show upgrade button when requiresUpgrade=false", () => {
      render(
        <WorkflowCard
          {...defaultProps}
          locked={true}
          requiresUpgrade={false}
        />,
      );

      expect(screen.queryByText("Upgrade Now")).not.toBeInTheDocument();
    });
  });

  describe("Metrics Display", () => {
    const metricsProps = {
      ...defaultProps,
      metrics: [
        {
          label: "Messages Sent",
          value: 1234,
          icon: <MessageSquare data-testid="metric-icon-1" />,
        },
        {
          label: "Active Users",
          value: "56",
          icon: <Users data-testid="metric-icon-2" />,
        },
      ],
    };

    it("should display all metrics", () => {
      render(<WorkflowCard {...metricsProps} />);

      expect(screen.getByText("Messages Sent")).toBeInTheDocument();
      expect(screen.getByText("1234")).toBeInTheDocument();
      expect(screen.getByText("Active Users")).toBeInTheDocument();
      expect(screen.getByText("56")).toBeInTheDocument();
    });

    it("should display metric icons", () => {
      render(<WorkflowCard {...metricsProps} />);

      expect(screen.getByTestId("metric-icon-1")).toBeInTheDocument();
      expect(screen.getByTestId("metric-icon-2")).toBeInTheDocument();
    });

    it("should render metrics in 2-column grid", () => {
      const { container } = render(<WorkflowCard {...metricsProps} />);

      const metricsGrid = container.querySelector(".grid.grid-cols-2");
      expect(metricsGrid).toBeInTheDocument();
    });

    it("should not render metrics section when metrics array is empty", () => {
      const { container } = render(
        <WorkflowCard {...defaultProps} metrics={[]} />,
      );

      const metricsGrid = container.querySelector(".grid.grid-cols-2");
      expect(metricsGrid).not.toBeInTheDocument();
    });
  });

  describe("Last Run Info", () => {
    it("should display last run time", () => {
      const lastRun = new Date(Date.now() - 3600000); // 1 hour ago
      render(<WorkflowCard {...defaultProps} lastRun={lastRun} />);

      expect(screen.getByText(/Last run:/i)).toBeInTheDocument();
      expect(screen.getByText(/1 hours ago/i)).toBeInTheDocument();
    });

    it("should display last run status", () => {
      const lastRun = new Date(Date.now() - 3600000);
      render(
        <WorkflowCard
          {...defaultProps}
          lastRun={lastRun}
          lastRunStatus="Completed successfully"
        />,
      );

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

    it('should format "just now" for recent runs', () => {
      const lastRun = new Date(Date.now() - 30000); // 30 seconds ago
      render(<WorkflowCard {...defaultProps} lastRun={lastRun} />);

      expect(screen.getByText(/Just now/i)).toBeInTheDocument();
    });

    it("should not display last run section when lastRun is undefined", () => {
      render(<WorkflowCard {...defaultProps} />);

      expect(screen.queryByText(/Last run:/i)).not.toBeInTheDocument();
    });
  });

  describe("Action Buttons", () => {
    it("should call onActivate when Activate button is clicked", () => {
      const onActivate = jest.fn();
      render(
        <WorkflowCard
          {...defaultProps}
          status="inactive"
          onActivate={onActivate}
        />,
      );

      const activateButton = screen.getByText("Activate");
      fireEvent.click(activateButton);

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

    it("should call onDeactivate when Deactivate button is clicked", () => {
      const onDeactivate = jest.fn();
      render(
        <WorkflowCard
          {...defaultProps}
          status="active"
          onDeactivate={onDeactivate}
        />,
      );

      const deactivateButton = screen.getByText("Deactivate");
      fireEvent.click(deactivateButton);

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

    it("should call onConfigure when Configure button is clicked", () => {
      const onConfigure = jest.fn();
      render(<WorkflowCard {...defaultProps} onConfigure={onConfigure} />);

      const configureButton = screen.getByLabelText(/configure workflow/i);
      fireEvent.click(configureButton);

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

    it("should show Retry button for error status", () => {
      render(
        <WorkflowCard
          {...defaultProps}
          status="error"
          onActivate={jest.fn()}
        />,
      );

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

    it("should not show Activate button when onActivate is not provided", () => {
      render(<WorkflowCard {...defaultProps} status="inactive" />);

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

    it("should not show Configure button when onConfigure is not provided", () => {
      render(<WorkflowCard {...defaultProps} />);

      expect(
        screen.queryByLabelText(/configure workflow/i),
      ).not.toBeInTheDocument();
    });
  });

  describe("Loading State", () => {
    it("should disable buttons when loading=true", () => {
      render(
        <WorkflowCard
          {...defaultProps}
          status="inactive"
          loading={true}
          onActivate={jest.fn()}
          onConfigure={jest.fn()}
        />,
      );

      const activateButton = screen
        .getByText("Activating...")
        .closest("button");
      const configureButton = screen.getByLabelText(/configure workflow/i);

      expect(activateButton).toBeDisabled();
      expect(configureButton).toBeDisabled();
    });

    it("should show loading overlay when loading=true", () => {
      render(<WorkflowCard {...defaultProps} loading={true} />);

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

    it("should show loading text for activate button", () => {
      render(
        <WorkflowCard
          {...defaultProps}
          status="inactive"
          loading={true}
          onActivate={jest.fn()}
        />,
      );

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

    it("should show loading text for deactivate button", () => {
      render(
        <WorkflowCard
          {...defaultProps}
          status="active"
          loading={true}
          onDeactivate={jest.fn()}
        />,
      );

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

    it("should show loading text for retry button", () => {
      render(
        <WorkflowCard
          {...defaultProps}
          status="error"
          loading={true}
          onActivate={jest.fn()}
        />,
      );

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

  describe("CSS Classes and Styling", () => {
    it("should apply border color for active status", () => {
      const { container } = render(
        <WorkflowCard {...defaultProps} status="active" />,
      );

      const card = container.firstChild;
      expect(card).toHaveClass("border-emerald-300");
    });

    it("should apply border color for error status", () => {
      const { container } = render(
        <WorkflowCard {...defaultProps} status="error" />,
      );

      const card = container.firstChild;
      expect(card).toHaveClass("border-red-300");
    });

    it("should apply border color for locked status", () => {
      const { container } = render(
        <WorkflowCard {...defaultProps} locked={true} />,
      );

      const card = container.firstChild;
      expect(card).toHaveClass("border-amber-300");
    });

    it("should apply opacity when loading", () => {
      const { container } = render(
        <WorkflowCard {...defaultProps} loading={true} />,
      );

      const card = container.firstChild;
      expect(card).toHaveClass("opacity-75");
    });
  });

  describe("RTL Support", () => {
    it("should support RTL layout (no hardcoded left/right)", () => {
      const { container } = render(<WorkflowCard {...defaultProps} />);

      // Component uses flex and gap (RTL-compatible)
      // No hardcoded left/right margins or padding
      const card = container.firstChild;
      expect(card).toBeInTheDocument();
    });
  });

  describe("Edge Cases", () => {
    it("should handle empty metrics array", () => {
      render(<WorkflowCard {...defaultProps} metrics={[]} />);

      expect(screen.getByText(defaultProps.title)).toBeInTheDocument();
    });

    it("should handle missing optional props", () => {
      render(
        <WorkflowCard
          title="Test"
          description="Test description"
          status="active"
        />,
      );

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

    it("should handle very long titles", () => {
      const longTitle =
        "This is a very long title that should be truncated to fit within the card layout properly";
      const { container } = render(
        <WorkflowCard {...defaultProps} title={longTitle} />,
      );

      const titleElement = screen.getByText(longTitle);
      expect(titleElement).toHaveClass("truncate");
    });

    it("should handle very long descriptions", () => {
      const longDescription =
        "This is a very long description that should be clamped to a maximum of 2 lines to maintain consistent card height across the layout";
      const { container } = render(
        <WorkflowCard {...defaultProps} description={longDescription} />,
      );

      const descElement = screen.getByText(longDescription);
      expect(descElement).toHaveClass("line-clamp-2");
    });
  });
});
