"use client";

import { cn } from "@/lib/utils";
import {
  ReactElement,
  ReactNode,
  cloneElement,
  isValidElement,
} from "react";
import { useRouter } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { PRIMARY_COLOR } from "@/lib/common";

interface BreadcrumbItem {
  label: string;
  href?: string;
}

interface FormSectionHeadingProps {
  title: string;
  icon?: ReactNode;
  eyebrow?: string;
  description?: string;
  breadcrumbs?: BreadcrumbItem[];
  showBackButton?: boolean;
  className?: string;
}

export function FormSectionHeading({
  title,
  icon,
  eyebrow,
  description,
  breadcrumbs = [],
  showBackButton = false,
  className,
}: FormSectionHeadingProps) {
  let renderedIcon: ReactNode = null;
  const router = useRouter();

  if (icon) {
    if (isValidElement(icon)) {
      const iconElement = icon as ReactElement<{ className?: string }>;
      renderedIcon = cloneElement(iconElement, {
        className: cn("text-2xl text-current", iconElement.props.className ?? ""),
      });
    } else {
      renderedIcon = icon;
    }
  }

  return (
    <div
      className={cn(
        "relative overflow-hidden rounded-lg border bg-gradient-to-r from-white via-opacity-5 to-white px-5 py-4 shadow-sm",
        "before:absolute before:inset-y-0 before:left-0 before:w-1",
        "after:pointer-events-none after:absolute after:-right-16 after:-top-8 after:h-40 after:w-40 after:rounded-lg after:opacity-10 after:blur-3xl",
        className
      )}
      style={{
        borderColor: `${PRIMARY_COLOR}33`,
        background: `linear-gradient(to right, white, ${PRIMARY_COLOR}0D, white)`,
        // @ts-ignore - dynamic style
        "--before-bg": PRIMARY_COLOR,
        "--after-bg": PRIMARY_COLOR,
      }}
      // @ts-ignore - dynamic style
      ref={(el: HTMLDivElement | null) => {
        if (el) {
          const beforeEl = el.querySelector(":before") as HTMLElement;
          const afterEl = el.querySelector(":after") as HTMLElement;
          if (beforeEl) beforeEl.style.backgroundColor = PRIMARY_COLOR;
          if (afterEl) afterEl.style.backgroundColor = PRIMARY_COLOR;
        }
      }}
    >
      <div className="relative z-10 flex flex-col gap-2.5">
        {breadcrumbs.length > 0 && (
          <nav aria-label="Breadcrumb">
            <ol className="flex flex-wrap items-center gap-1 text-[11px] font-medium uppercase tracking-[0.25em] text-slate-500">
              {breadcrumbs.map((crumb, index) => {
                const isLast = index === breadcrumbs.length - 1;
                return (
                  <li key={`${crumb.label}-${index}`} className="flex items-center gap-1">
                    <span
                      className={cn(
                        "transition-colors",
                        isLast ? "" : "text-slate-500"
                      )}
                      style={{ color: isLast ? PRIMARY_COLOR : undefined }}
                      onMouseEnter={(e) => {
                        if (!isLast) {
                          e.currentTarget.style.color = PRIMARY_COLOR;
                        }
                      }}
                      onMouseLeave={(e) => {
                        if (!isLast) {
                          e.currentTarget.style.color = "";
                        }
                      }}
                    >
                      {crumb.href && !isLast ? (
                        <a href={crumb.href}>{crumb.label}</a>
                      ) : (
                        crumb.label
                      )}
                    </span>
                    {!isLast && <span className="text-slate-400">/</span>}
                  </li>
                );
              })}
            </ol>
          </nav>
        )}

        <div className="flex items-center gap-3">
          {showBackButton && (
            <button
              type="button"
              onClick={() => router.back()}
              className="inline-flex h-8 w-8 items-center justify-center rounded-lg border transition"
              style={{
                borderColor: `${PRIMARY_COLOR}4D`,
                color: PRIMARY_COLOR,
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.borderColor = PRIMARY_COLOR;
                e.currentTarget.style.backgroundColor = PRIMARY_COLOR;
                e.currentTarget.style.color = "white";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.borderColor = `${PRIMARY_COLOR}4D`;
                e.currentTarget.style.backgroundColor = "";
                e.currentTarget.style.color = PRIMARY_COLOR;
              }}
              aria-label="Go back"
            >
              <ArrowLeft className="h-4 w-4" />
            </button>
          )}
          {renderedIcon && (
            <span 
              className="flex h-10 w-10 items-center justify-center rounded-lg"
              style={{
                backgroundColor: `${PRIMARY_COLOR}1A`,
                color: PRIMARY_COLOR,
              }}
            >
              {renderedIcon}
            </span>
          )}

          <div>
            {eyebrow && (
              <p 
                className="text-xs font-semibold uppercase tracking-[0.25em]"
                style={{ color: `${PRIMARY_COLOR}B3` }}
              >
                {eyebrow}
              </p>
            )}
            <h2 className="text-lg font-semibold text-slate-800 tracking-wide">
              {title}
            </h2>
            {description && (
              <p className="mt-1 text-sm text-slate-500">{description}</p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
