"use client";

import { clsx } from "clsx";
import { memo, useMemo, useState } from "react";
import { useTimelineContext } from "./TimelineContext.js";
import { getProjectColor } from "~/lib/project-colors.js";
import { FadeIn } from "~/components/ui/FadeIn.js";

function ProjectColorLegendInner() {
  const { visibleAssignments, viewMode, projectGroups } = useTimelineContext();
  const [dismissed, setDismissed] = useState(false);

  // Collect unique visible projects with their colors
  const legendItems = useMemo(() => {
    const seen = new Map<string, { shortCode: string; name: string; hex: string }>();

    if (viewMode === "project") {
      for (const group of projectGroups) {
        if (seen.has(group.id)) continue;
        const customColor = group.color;
        const projectColor = getProjectColor(group.id);
        seen.set(group.id, {
          shortCode: group.shortCode,
          name: group.name,
          hex: customColor ?? projectColor.hex,
        });
      }
    } else {
      for (const entry of visibleAssignments) {
        if (seen.has(entry.projectId)) continue;
        const customColor = (entry.project as { color?: string | null }).color;
        const projectColor = getProjectColor(entry.projectId);
        seen.set(entry.projectId, {
          shortCode: entry.project.shortCode,
          name: entry.project.name,
          hex: customColor ?? projectColor.hex,
        });
      }
    }

    return [...seen.values()].sort((a, b) => a.shortCode.localeCompare(b.shortCode));
  }, [visibleAssignments, viewMode, projectGroups]);

  if (dismissed || legendItems.length === 0) return null;

  return (
    <FadeIn>
      <div className="flex items-center gap-1 px-3 py-1.5 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg shadow-sm overflow-x-auto scrollbar-thin">
        <span className="text-[10px] font-medium text-gray-400 dark:text-gray-500 flex-shrink-0 mr-1">
          Projects
        </span>
        <div className="flex items-center gap-2.5 min-w-0">
          {legendItems.map((item) => (
            <div
              key={item.shortCode}
              className="flex items-center gap-1 flex-shrink-0"
              title={item.name}
            >
              <div
                className="w-2.5 h-2.5 rounded-full flex-shrink-0"
                style={{ backgroundColor: item.hex }}
              />
              <span className="text-[10px] font-medium text-gray-600 dark:text-gray-300 whitespace-nowrap">
                {item.shortCode}
              </span>
            </div>
          ))}
        </div>
        <button
          type="button"
          onClick={() => setDismissed(true)}
          className={clsx(
            "ml-2 flex-shrink-0 w-4 h-4 flex items-center justify-center rounded",
            "text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300",
            "hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors",
          )}
          aria-label="Dismiss color legend"
        >
          <svg className="w-3 h-3" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M2 2l8 8M10 2l-8 8" />
          </svg>
        </button>
      </div>
    </FadeIn>
  );
}

export const ProjectColorLegend = memo(ProjectColorLegendInner);
