import React, { useState, useEffect } from "react";
import { generateCalendarData } from "../utils/calendar";
import {
  OpenSourceHeatmapProps,
  ProviderInfo,
  ModelData,
} from "../types/heatmap";
import Heatmap from "../components/Heatmap";
import { fetchAllProvidersData, fetchAllAuthorsData } from "../utils/authors";

const PROVIDERS: ProviderInfo[] = [
  { color: "#ff7000", authors: ["mistralai"] },
  { color: "#1877F2", authors: ["meta-llama", "facebook", ] },
  { color: "#10A37F", authors: ["openai"] },
  { color: "#cc785c", authors: ["Anthropic"] },
  { color: "#DB4437", authors: ["google"] },
  { color: "#5E35B1", authors: ["allenai"] },
  { color: "#0088cc", authors: ["apple"] },
  { color: "#FEB800", authors: ["microsoft"] },
  { color: "#76B900", authors: ["nvidia"] },
  { color: "#0088cc", authors: ["deepseek-ai"] },
  { color: "#0088cc", authors: ["Qwen"] },
  { color: "#4C6EE6", authors: ["CohereForAI"] },
  { color: "#4C6EE6", authors: ["ibm-granite"] },
  { color: "#A020F0", authors: ["stabilityai"] },
];

export async function getStaticProps() {
  try {
    const allAuthors = PROVIDERS.flatMap(({ authors }) => authors);
    const uniqueAuthors = Array.from(new Set(allAuthors));

    const flatData: ModelData[] = await fetchAllAuthorsData(uniqueAuthors);
    const updatedProviders = await fetchAllProvidersData(PROVIDERS);

    const calendarData = generateCalendarData(flatData, updatedProviders);

    return {
      props: {
        calendarData,
        providers: updatedProviders,
      },
      revalidate: 3600, // regenerate every hour
    };
  } catch (error) {
    console.error("Error fetching data:", error);
    return {
      props: {
        calendarData: {},
        providers: PROVIDERS,
      },
      revalidate: 60, // retry after 1 minute if there was an error
    };
  }
}

const OpenSourceHeatmap: React.FC<OpenSourceHeatmapProps> = ({
  calendarData,
  providers,
}) => {
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (calendarData && Object.keys(calendarData).length > 0) {
      setIsLoading(false);
    }
  }, [calendarData]);

  return (
    <div className="w-full max-w-screen-lg mx-auto p-4">
      <h1 className="text-3xl lg:text-5xl mt-16 font-bold text-center mb-2">
        Hugging Face Heatmap 🤗
      </h1>
      <p className="text-center text-sm my-8">
        Models, Datasets, and Spaces from the top AI labs. <br />
        Request more heatmaps by{" "}
        <a
          href="https://huggingface.co/spaces/cfahlgren1/model-release-heatmap/discussions/new"
          target="_blank"
          rel="noopener noreferrer"
          className="text-blue-500 hover:underline"
        >
          opening a discussion
        </a>
        .
      </p>
      {isLoading ? (
        <p className="text-center">Loading...</p>
      ) : (
        <div className="space-y-16">
          {providers
            .sort((a, b) =>
              calendarData[b.fullName || b.authors[0]].reduce(
                (sum, day) => sum + day.count,
                0
              ) -
              calendarData[a.fullName || a.authors[0]].reduce(
                (sum, day) => sum + day.count,
                0
              )
            )
            .map((provider) => {
              const providerName = provider.fullName || provider.authors[0];
              return (
                <div key={providerName} className="flex flex-col items-center">
                  <Heatmap
                    data={calendarData[providerName]}
                    color={provider.color}
                    providerName={providerName}
                    fullName={provider.fullName ?? providerName}
                    avatarUrl={provider.avatarUrl ?? ''}
                  />
                </div>
              );
            })}
        </div>
      )}
    </div>
  );
};

export default OpenSourceHeatmap;