import { Check, Map } from "lucide-react";
import { type FocusEvent, useCallback, useEffect, useRef, useState } from "react";
import { cn } from "@/shared/ui/cn";
import {
  MAP_CONTROL_RADIUS_CLASS_NAME,
  MAP_CONTROL_SURFACE_CLASS_NAME,
  MAP_ICON_CELL_RADIUS_CLASS_NAME,
  MAP_MAJOR_PANEL_RADIUS_CLASS_NAME,
  MAP_READABLE_RADIUS_CLASS_NAME,
  MAP_READABLE_SURFACE_CLASS_NAME,
  MAP_TOOL_PANEL_SURFACE_CLASS_NAME
} from "./map-control-styles";

export type BaseLayerOption = {
  id: string;
  label: string;
  description?: string;
  disabled?: boolean;
  swatchClassName?: string;
};

type BaseLayersControlProps = {
  options: BaseLayerOption[];
  activeLayerId: string;
  onSelectLayer: (id: string) => void;
  title?: string;
  variant?: "floating" | "panel";
  className?: string;
};

export function BaseLayersControl({
  options,
  activeLayerId,
  onSelectLayer,
  title = "底图",
  variant = "floating",
  className = ""
}: BaseLayersControlProps) {
  const activeLayer = options.find((option) => option.id === activeLayerId) ?? options[0];
  const [isOpen, setIsOpen] = useState(false);
  const closeTimerRef = useRef<number | null>(null);

  const clearCloseTimer = useCallback(() => {
    if (closeTimerRef.current) {
      window.clearTimeout(closeTimerRef.current);
      closeTimerRef.current = null;
    }
  }, []);

  const openControl = useCallback(() => {
    clearCloseTimer();
    setIsOpen(true);
  }, [clearCloseTimer]);

  const scheduleClose = useCallback(() => {
    clearCloseTimer();
    closeTimerRef.current = window.setTimeout(() => {
      setIsOpen(false);
      closeTimerRef.current = null;
    }, 260);
  }, [clearCloseTimer]);

  const handleBlur = useCallback(
    (event: FocusEvent<HTMLElement>) => {
      if (event.currentTarget.contains(event.relatedTarget)) {
        return;
      }

      scheduleClose();
    },
    [scheduleClose]
  );

  useEffect(() => clearCloseTimer, [clearCloseTimer]);

  if (variant === "panel") {
    return (
      <section
        aria-label={title}
        className={cn(
          "pointer-events-auto w-[276px] p-3",
          MAP_MAJOR_PANEL_RADIUS_CLASS_NAME,
          MAP_TOOL_PANEL_SURFACE_CLASS_NAME,
          className
        )}
      >
        <div className="flex items-center gap-2 px-1">
          <span className={cn("grid h-8 w-8 shrink-0 place-items-center bg-blue-50 text-blue-700", MAP_ICON_CELL_RADIUS_CLASS_NAME)}>
            <Map size={17} aria-hidden="true" />
          </span>
          <div className="min-w-0">
            <h2 className="truncate text-sm font-semibold leading-tight text-slate-950">{title}</h2>
            <p className="mt-0.5 truncate text-xs text-slate-500">
              当前 {activeLayer?.label ?? "--"}
            </p>
          </div>
        </div>

        <div className="mt-3 grid grid-cols-3 gap-2">
          {options.map((option) => {
            const active = option.id === activeLayerId;

            return (
              <button
                key={option.id}
                type="button"
                disabled={option.disabled}
                aria-pressed={active}
                onClick={() => onSelectLayer(option.id)}
                className={cn(
                  "flex min-h-[76px] flex-col p-1 text-left transition duration-150",
                  MAP_READABLE_RADIUS_CLASS_NAME,
                  MAP_READABLE_SURFACE_CLASS_NAME,
                  active
                    ? "border-blue-500 text-blue-700 shadow-xs ring-2 ring-blue-100"
                    : "text-slate-700 hover:border-blue-300 hover:bg-blue-50/40",
                  option.disabled && "cursor-not-allowed opacity-50"
                )}
              >
                <BaseLayerSwatch option={option} active={active} />
                <span className="mt-1 block w-full truncate px-0.5 text-xs font-semibold leading-none">
                  {option.label}
                </span>
              </button>
            );
          })}
        </div>
      </section>
    );
  }

  return (
    <section
      aria-label={title}
      onMouseEnter={openControl}
      onMouseLeave={scheduleClose}
      onFocus={openControl}
      onBlur={handleBlur}
      className={cn(
        "pointer-events-auto relative flex h-[96px] items-end justify-end",
        isOpen ? "w-[384px]" : "w-[96px]",
        className
      )}
    >
      <div
        className={cn(
          "absolute bottom-0 right-[104px] grid h-[96px] grid-cols-[repeat(3,84px)] gap-2 p-1.5 transition-opacity duration-150",
          MAP_CONTROL_RADIUS_CLASS_NAME,
          MAP_CONTROL_SURFACE_CLASS_NAME,
          isOpen ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0"
        )}
      >
        {options.map((option) => {
          const active = option.id === activeLayerId;

          return (
            <button
              key={option.id}
              type="button"
              disabled={option.disabled}
              aria-pressed={active}
              onClick={() => onSelectLayer(option.id)}
              className={cn(
                "flex h-[84px] w-[84px] flex-col p-1 text-center transition duration-150",
                MAP_READABLE_RADIUS_CLASS_NAME,
                MAP_READABLE_SURFACE_CLASS_NAME,
                active ? "border-blue-500 shadow-xs ring-2 ring-blue-100" : "border-slate-200 hover:border-blue-300 hover:bg-blue-50/40",
                option.disabled && "cursor-not-allowed opacity-50"
              )}
            >
              <BaseLayerSwatch option={option} active={active} />
              <span
                data-base-layer-label="true"
                className="block h-4 shrink-0 truncate px-0.5 pt-1 text-xs font-semibold leading-none text-slate-800"
              >
                {option.label}
              </span>
            </button>
          );
        })}
      </div>
      <div className={cn("absolute bottom-0 right-0 grid h-[96px] w-[96px] place-items-center p-1.5", MAP_CONTROL_RADIUS_CLASS_NAME, MAP_CONTROL_SURFACE_CLASS_NAME)}>
        <button
          type="button"
          aria-label={`${title}：当前 ${activeLayer?.label ?? ""}`}
          title={`${title}：当前 ${activeLayer?.label ?? ""}`}
          className={cn("grid h-[84px] w-[84px] place-items-center p-1 text-slate-700 shadow-xs transition hover:border-blue-300 hover:text-blue-700", MAP_READABLE_RADIUS_CLASS_NAME, MAP_READABLE_SURFACE_CLASS_NAME)}
        >
          <span className={cn("relative h-full w-full overflow-hidden border border-white shadow-inner", MAP_ICON_CELL_RADIUS_CLASS_NAME)}>
            {activeLayer ? (
              <span className={cn("absolute inset-0", activeLayer.swatchClassName ?? "bg-slate-100")} />
            ) : (
              <Map size={18} aria-hidden="true" className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2" />
            )}
            <span className="surface-reading absolute bottom-1 left-1 right-1 rounded px-1 py-0.5 text-xs font-semibold leading-none text-slate-800">
              {activeLayer?.label ?? title}
            </span>
          </span>
        </button>
      </div>
    </section>
  );
}

type BaseLayerSwatchProps = {
  option: BaseLayerOption;
  active: boolean;
};

function BaseLayerSwatch({ option, active }: BaseLayerSwatchProps) {
  return (
    <span
      className={cn(
        "relative block min-h-0 flex-1 overflow-hidden border border-white shadow-inner",
        MAP_ICON_CELL_RADIUS_CLASS_NAME,
        option.swatchClassName ?? "bg-slate-100"
      )}
    >
      {active ? (
        <span className="absolute right-0.5 top-0.5 grid h-4 w-4 place-items-center rounded-full bg-blue-600 text-white shadow-xs">
          <Check size={10} aria-hidden="true" />
        </span>
      ) : null}
    </span>
  );
}
