"use client";

import React, { forwardRef } from "react";
import { cx } from "../../utils/cx";
import { LinkProps } from "./types";
import NextLinkImport from "next/link";

// Handle CJS/ESM interop: when bundled as ESM and consumed by Webpack,
// the default import may resolve to { default: Component } instead of the function.
const NextLink =
  typeof NextLinkImport === "function"
    ? NextLinkImport
    : ((NextLinkImport as any).default ?? NextLinkImport);

export const Link = forwardRef<HTMLAnchorElement, LinkProps>(
  (
    {
      children,
      href,
      className = "",
      onClick,
      variant = "unstyled",
      style,
      external = false,
      disabled = false,
      ...props
    },
    ref
  ) => {
    // Get Tailwind classes for different variants
    const getVariantClasses = () => {
      if (variant === "unstyled") return "";

      // TODO: Add styles based on the figma design for all variants
      const baseClasses =
        "transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2";

      const variantClasses = {
        default: "text-text underline",
      };

      const stateClasses = [
        disabled
          ? "opacity-60 cursor-not-allowed pointer-events-none"
          : "cursor-pointer",
      ]
        .filter(Boolean)
        .join(" ");

      return [
        baseClasses,
        variantClasses[variant as keyof typeof variantClasses] ||
          variantClasses.default,
        stateClasses,
      ]
        .filter(Boolean)
        .join(" ");
    };

    const tailwindClasses = getVariantClasses();

    // Handle click events
    const handleClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
      if (disabled) {
        event.preventDefault();
        return;
      }

      onClick?.(event);
    };

    // Combine all classes
    const combinedClassName = cx(
      tailwindClasses,
      `link--${variant}`,
      disabled && "link--disabled",
      className
    );

    // Determine link props based on external/internal
    const linkProps = {
      ...props,
      ref,
      className: combinedClassName,
      style,
      href: disabled ? undefined : href,
      onClick: handleClick,
      ...(external &&
        !disabled && {
          target: "_blank",
          rel: "noopener",
        }),
      ...(disabled && {
        "aria-disabled": true,
        tabIndex: -1,
      }),
    };

    if (
      disabled ||
      external ||
      (typeof href === "string" && href.startsWith("http"))
    ) {
      return <a {...linkProps}>{children}</a>;
    }
    return (
      <NextLink
        href={href || "#"}
        ref={ref}
        className={combinedClassName}
        style={style}
        onClick={handleClick}
        {...props}
      >
        {children}
      </NextLink>
    );
  }
);

Link.displayName = "Link";

export type { LinkProps };
