"use client";

import React, { useMemo } from "react";
import { cn } from "@/lib/utils";
import type { ColumnTypeInfo } from "./types";
import { INPUT_TYPE_COLORS } from "./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.inputType || "text";
    counts[t] = (counts[t] || 0) + 1;
  }
  return counts;
}

/** 도넛 차트용 비율 (0~1) 배열 및 라벨 순서 */
function getDonutSegments(counts: Record<string, number>, total: number): Array<{ type: string; ratio: number }> {
  const order = Object.keys(INPUT_TYPE_COLORS);
  return order
    .filter((type) => (counts[type] || 0) > 0)
    .map((type) => ({ type, ratio: (counts[type] || 0) / total }));
}

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 segmentPaths = segments.map(({ type, ratio }) => {
    const length = ratio * circumference;
    const dashArray = `${length} ${circumference - length}`;
    const dashOffset = -offset;
    offset += length;
    const conf = INPUT_TYPE_COLORS[type] || { color: "text-muted-foreground", bgColor: "bg-muted" };
    return {
      type,
      dashArray,
      dashOffset,
      ...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>

      {/* 타입 칩 목록 (클릭 시 필터 토글) */}
      <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">
        {Object.entries(counts)
          .sort((a, b) => (b[1] ?? 0) - (a[1] ?? 0))
          .map(([type]) => {
            const conf = INPUT_TYPE_COLORS[type] || { color: "text-muted-foreground", bgColor: "bg-muted", 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>
            );
          })}
      </div>
    </div>
  );
}
