"use client";
import { events } from "@/lib/events";
import { LinkIcon } from "lucide-react";
import { useEffect, useState, useRef } from "react";
import { Button } from "@/components/ui/button";

export default function TimelineComponent() {
  const [selectedYear, setSelectedYear] = useState<number | null>(null);

  const years = Array.from(
    new Set(events.map((event) => new Date(event.date).getFullYear()))
  ).sort((a, b) => b - a);

  useEffect(() => {
    if (years.length > 0 && selectedYear === null) {
      setSelectedYear(years[0]);
    }
  }, [years, selectedYear]);

  const filteredEvents = selectedYear
    ? events.filter(
        (event) => new Date(event.date).getFullYear() === selectedYear
      )
    : [];

  return (
    <div
      id="timeline"
      className="w-full flex flex-col items-center justify-center mt-8"
    >
      <div className="w-full">
        <h1 className="text-2xl font-bold mb-4 w-full">🌠 수상 및 교육</h1>
        <br />
        <div className="flex flex-col md:flex-row gap-4 h-full">
          {/* Left column - Year buttons */}
          <div className="w-full md:w-24 flex flex-row md:flex-col gap-2 overflow-y-auto pr-2">
            {years.map((year) => (
              <Button
                key={year}
                onClick={() => setSelectedYear(year)}
                variant={selectedYear === year ? "default" : "outline"}
                className="font-semibold"
              >
                {year}
              </Button>
            ))}
          </div>

          {/* Right column - Events */}
          <div className="flex-1 overflow-y-auto pr-2">
            <div className="space-y-2">
              {filteredEvents.map((event, index) => (
                <div
                  key={index}
                  className="rounded-lg border bg-background px-4 py-3"
                >
                  <div className="flex flex-row gap-2 mb-1">
                    <span className="text-md font-semibold fixed-width-number">
                      {new Date(event.date).toLocaleDateString("en-US", {
                        month: "short",
                        day: "2-digit",
                      })}
                    </span>
                    <span className="text-md font-semibold fixed-width-number text-muted-foreground">
                      ㆍ{event.category}
                    </span>
                  </div>
                  {event.link ? (
                    <a href={event.link} className="">
                      {event.description}{" "}
                      <LinkIcon className="inline-block w-4 h-4 mb-1 ml-1" />
                    </a>
                  ) : (
                    <span>{event.description}</span>
                  )}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
