"use client";

import { useMemo } from "react";
import { cn } from "@/lib/utils";
import type { Result } from "@/lib/types";
import { DateGroup } from "./date-group";

// Type for date-grouped results
type DateGroupedResults = {
  [date: string]: {
    date: string;
    runs: Result[];
  };
};

interface FoldableListProps {
  results: Result[];
  className?: string;
}

export function FoldableList({ results, className }: FoldableListProps) {
  if (!results[0]?.run_id)
    return (
      <h1 className="text-center text-red-400">
        There was an Error while fetching test results.
      </h1>
    );
  // Group results by date
  const dateGroupedResults = useMemo(() => {
    const grouped: DateGroupedResults = {};

    results.forEach((result) => {
      const date = new Date(result.date).toDateString();

      if (!grouped[date]) {
        grouped[date] = {
          date,
          runs: [],
        };
      }

      grouped[date].runs.push(result);
    });

    // Convert to array and sort by date (newest first)
    return Object.values(grouped).sort(
      (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
    );
  }, [results]);

  return (
    <div className={cn("w-full", className)}>
      {dateGroupedResults.map((dateGroup) => (
        <DateGroup key={dateGroup.date} dateGroup={dateGroup} />
      ))}
    </div>
  );
}
