"use client";

import React, { useMemo } from "react";
import { cn } from "@/lib/utils";
import type { ColumnTypeInfo } from "./types";
import { INPUT_TYPE_COLORS, FALLBACK_TYPE_CONFIG } from "./types";
import { USER_SELECTABLE_INPUT_TYPE_ORDER } from "@/types/input-types";

export interface TypeOverviewStripProps {
  columns: ColumnTypeInfo[];
  activeFilter?: string | null;
  onFilterChange?: (type: string | null) => void;
}

/** inputType별 카운트 계산 */
function countByInputType(columns: ColumnTypeInfo[]): Record<string, number> {
  const counts: Record<string, number> = {};
  for (const col of columns) {
    const t = col.input_type || "text";
    counts[t] = (counts[t] || 0) + 1;
  }
  return counts;
}

/** 도넛 차트용 segment (8개 base + legacy 그룹) */
function getDonutSegments(
  counts: Record<string, number>,
  total: number,
): Array<{ type: string; ratio: number; isLegacy: boolean }> {
  const baseSegments = (USER_SELECTABLE_INPUT_TYPE_ORDER as readonly string[])
    .filter((type) => (counts[type] || 0) > 0)
    .map((type) => ({ type, ratio: (counts[type] || 0) / total, isLegacy: false }));

  const legacyCount = Object.entries(counts)
    .filter(([type]) => !(USER_SELECTABLE_INPUT_TYPE_ORDER as readonly string[]).includes(type))
    .reduce((sum, [, count]) => sum + count, 0);

  if (legacyCount > 0) {
    baseSegments.push({ type: "__legacy__", ratio: legacyCount / total, isLegacy: true });
  }

  return baseSegments;
}

export function TypeOverviewStrip({
  columns,
  activeFilter = null,
  onFilterChange,
}: TypeOverviewStripProps) {
  const { counts, total, segments } = useMemo(() => {
    const counts = countByInputType(columns);
    const total = columns.length || 1;
    const segments = getDonutSegments(counts, total);
    return { counts, total, segments };
  }, [columns]);

  /** stroke-dasharray: 비율만큼 둘레에 할당 (둘레 100 기준) */
  const circumference = 100;
  let offset = 0;
  const LEGACY_CONF = { ...FALLBACK_TYPE_CONFIG, color: "text-amber-600", bgColor: "bg-amber-50", barColor: "bg-amber-400" };
  const segmentPaths = segments.map(({ type, ratio, isLegacy }) => {
    const length = ratio * circumference;
    const dashArray = `${length} ${circumference - length}`;
    const dashOffset = -offset;
    offset += length;
    const conf = isLegacy ? LEGACY_CONF : (INPUT_TYPE_COLORS[type] || FALLBACK_TYPE_CONFIG);
    return {
      type,
      dashArray,
      dashOffset,
      isLegacy,
      ...conf,
    };
  });

  return (
    <div className="flex flex-shrink-0 items-center gap-3 border-b bg-muted/30 px-5 py-2.5">
      {/* SVG 도넛 (원형 stroke) */}
      <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center">
        <svg className="h-10 w-10 -rotate-90" viewBox="0 0 36 36">
          {segmentPaths.map((seg) => (
            <g key={seg.type} className={cn(seg.color, "opacity-80")}>
              <circle
                cx="18"
                cy="18"
                r="14"
                fill="none"
                stroke="currentColor"
                strokeWidth="6"
                strokeDasharray={seg.dashArray}
                strokeDashoffset={seg.dashOffset}
                aria-hidden
              />
            </g>
          ))}
          {segments.length === 0 && (
            <circle cx="18" cy="18" r="14" fill="none" stroke="currentColor" strokeWidth="6" className="text-muted-foreground/50" />
          )}
        </svg>
      </div>

      {/* 타입 칩 목록 (8개 base + legacy 그룹, 클릭 시 필터 토글) */}
      <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">
        {(USER_SELECTABLE_INPUT_TYPE_ORDER as readonly string[])
          .filter((type) => (counts[type] || 0) > 0)
          .sort((a, b) => (counts[b] ?? 0) - (counts[a] ?? 0))
          .map((type) => {
            const conf = INPUT_TYPE_COLORS[type] || { ...FALLBACK_TYPE_CONFIG, label: type };
            const isActive = activeFilter === null || activeFilter === type;
            return (
              <button
                key={type}
                type="button"
                onClick={() => onFilterChange?.(activeFilter === type ? null : type)}
                className={cn(
                  "rounded-md border px-2 py-1 text-xs font-medium transition-colors",
                  conf.bgColor,
                  conf.color,
                  "border-current/20",
                  isActive ? "ring-1 ring-ring" : "opacity-70 hover:opacity-100",
                )}
              >
                {conf.label} {counts[type]}
              </button>
            );
          })}
        {/* Legacy 칩 — 8개 외 구버전 타입 합산 */}
        {(() => {
          const legacyCount = Object.entries(counts)
            .filter(([type]) => !(USER_SELECTABLE_INPUT_TYPE_ORDER as readonly string[]).includes(type))
            .reduce((sum, [, count]) => sum + count, 0);
          if (legacyCount === 0) return null;
          const isActive = activeFilter === null || activeFilter === "__legacy__";
          return (
            <button
              key="__legacy__"
              type="button"
              onClick={() => onFilterChange?.(activeFilter === "__legacy__" ? null : "__legacy__")}
              className={cn(
                "rounded-md border px-2 py-1 text-xs font-medium transition-colors",
                "bg-amber-50 text-amber-600",
                "border-amber-200",
                isActive ? "ring-1 ring-ring" : "opacity-70 hover:opacity-100",
              )}
            >
              Legacy {legacyCount}
            </button>
          );
        })()}
      </div>
    </div>
  );
}
