import Template from "components/window/Template";
// @ts-ignore
import { useState, FormEvent,  } from "react";
import { useRouter } from "next/router";
import { NextPage, GetStaticProps } from "next";
import { FullLegend, legends, LegendStats } from "helper/types";
import LegendGlobalGrid from "components/LegendGrid/LegendStatsGrid";
import { dehydrate, QueryClient, useQuery } from "@tanstack/react-query";
import axios, { AxiosResponse } from "axios";
import Seo from "components/SEO";
// import { legends_colors } from "helper/constants";
// import { getLegendById } from "helper";
// import {
//   BarChart,
//   Bar,
//   Cell,
//   XAxis,
//   YAxis,
//   CartesianGrid,
//   Tooltip,
//   Legend,
//   ResponsiveContainer,
// } from "recharts";
// import { useMediaQuery } from "hooks/useMediaQuery";
// import domtoimage from "dom-to-image";

const LegendStatsPage: NextPage<pageProps> = (props: pageProps) => {
  const { data } = useQuery([`legend-stats`], getLegendStats, {
    staleTime: 60 * 19 * 1000,
    cacheTime: 60 * 19 * 1000,
  });
  const [stats, setStats] = useState(data || []);
  const router = useRouter();
  // let sorted_legends;
  // // sort l by alphabetical order
  // sorted_legends = ;
  let sortedStats: LegendStats[] = stats?.sort(
    (l1: LegendStats, l2: LegendStats) => l2.playrate - l1.playrate
  );
  return (
    <>
      {/* @ts-ignore */}
      <Seo
        templateTitle="Legend statistics"
        description="View Legend statistics for Brawlhalla"
      />
      <Template useWindow>
        
          
            <div className="select_parent mb-8">
              <select
                onChange={async (e: FormEvent<HTMLSelectElement>) => {
                  if (e.currentTarget.value === undefined) return;
                  router.push(
                    `/legends/rankings/${e.currentTarget.value}/mastery`
                  );
                }}
              >
                <option disabled selected hidden>
                  Legend Rankings
                </option>
                {legends
                  .sort((a, b) => {
                    if (a.legend_name_key < b.legend_name_key) {
                      return -1;
                    }
                    if (a.legend_name_key > b.legend_name_key) {
                      return 1;
                    }
                    return 0;
                  })
                  .map((legend: FullLegend) => (
                    <option key={legend.legend_id} value={legend.legend_id}>
                      {legend.bio_name}
                    </option>
                  ))}
              </select>
              <select
                onChange={async (e: FormEvent<HTMLSelectElement>) => {
                  let newStats = stats;

                  switch (e.currentTarget.value) {
                    case "playrate":
                      // Sort stats by highest playrate
                      newStats = stats.sort(
                        (a: LegendStats, b: LegendStats) => {
                          return b.playrate - a.playrate;
                        }
                      );
                      setStats([...newStats]);
                      break;
                    case "winrate":
                      // Sort stats by highest winrate
                      newStats = stats.sort(
                        (a: LegendStats, b: LegendStats) => {
                          return b.winrate - a.winrate;
                        }
                      );
                      setStats([...newStats]);
                      break;
                    case "suicides":
                      // Sort stats by highest playrate
                      newStats = stats.sort(
                        (a: LegendStats, b: LegendStats) => {
                          return b.suicides - a.suicides;
                        }
                      );
                      setStats([...newStats]);
                      break;
                    case "falls":
                      // Sort stats by highest playrate
                      newStats = stats.sort(
                        (a: LegendStats, b: LegendStats) => {
                          return b.falls - a.falls;
                        }
                      );
                      setStats([...newStats]);
                      break;
                    case "kos":
                      // Sort stats by highest playrate
                      newStats = stats.sort(
                        (a: LegendStats, b: LegendStats) => {
                          return b.kos - a.kos;
                        }
                      );
                      setStats([...newStats]);
                      break;
                    case "dmg":
                      // Sort stats by highest damage
                      newStats = stats.sort(
                        (a: LegendStats, b: LegendStats) => {
                          return b.damagedealt - a.damagedealt;
                        }
                      );
                      setStats([...newStats]);
                      break;
                    case "dmg_taken":
                      // Sort stats by highest damage
                      newStats = stats.sort(
                        (a: LegendStats, b: LegendStats) => {
                          return b.damagetaken - a.damagetaken;
                        }
                      );
                      setStats([...newStats]);
                      break;

                    case "matchtime":
                      // Sort stats by highest match time
                      newStats = stats.sort(
                        (a: LegendStats, b: LegendStats) => {
                          return b.matchtime - a.matchtime;
                        }
                      );
                      setStats([...newStats]);

                      break;
                    default:
                      break;
                  }
                }}
              >
                <option disabled selected hidden>
                  Sort by
                </option>
                <option value={"playrate"}>Playrate</option>
                <option value={"winrate"}>Winrate</option>
                <option value={"suicides"}>Suicides</option>
                <option value={"falls"}>Falls</option>
                <option value={"kos"}>KOs</option>
                <option value={"dmg"}>Damage Dealt</option>
                <option value={"dmg_taken"}>Damage Taken</option>
                <option value={"matchtime"}>Match time</option>
              </select>
              <select
                defaultValue={"All"}
                onChange={async (e) => {
                  // Redirect to /${rank}
                  router.push(`/legends/${e.currentTarget.value}`);
                }}
              >
                <option value="All">All Ranks</option>
                <option value="Diamond">Diamond</option>
                <option value="Platinum">Platinum</option>
              </select>

              
            </div>
            <LegendGlobalGrid legends={stats} />
          
        
      </Template>
    </>
  );
};

// const ChartView: NextPage<{
//   data: LegendStats[];
//   setChartView: Dispatch<SetStateAction<boolean>>;
// }> = ({
//   data,
//   setChartView,
// }: {
//   data: LegendStats[];
//   setChartView: Dispatch<SetStateAction<boolean>>;
// }) => {
//   const playrateSortedLegends = data
//     .slice()
//     .sort((l1: LegendStats, l2: LegendStats) => l2.playrate - l1.playrate);
//   const winrateSortedLegends = data
//     .slice()
//     .sort((l1: LegendStats, l2: LegendStats) => l2.winrate - l1.winrate);
//   const matchtimeSortedLegends = data
//     .slice()
//     .sort((l1: LegendStats, l2: LegendStats) => l2.matchtime - l1.matchtime);
//   const kosSortedLegends = data
//     .slice()
//     .sort((l1: LegendStats, l2: LegendStats) => l2.kos - l1.kos);
//   const dmgDealtSortedLegends = data
//     .slice()
//     .sort(
//       (l1: LegendStats, l2: LegendStats) => l2.damagedealt - l1.damagedealt
//     );
//   const dmgTakenSortedLegends = data
//     .slice()
//     .sort(
//       (l1: LegendStats, l2: LegendStats) => l1.damagetaken - l2.damagetaken
//     );

//   const Title = ({ children, desc }: { children: any; desc?: string }) => (
//     <div
//       style={{
//         fontFamily: "Coda-64",
//         textAlign: "center",
//         color: "rgb(255 203 119 / 1)",
//         fontWeight: "bold",
//       }}
//     >
//       <h2
//         style={{
//           fontSize: "2.25rem" /* 36px */,
//           lineHeight: "2.5rem" /* 40px */,
//         }}
//       >
//         {children}:
//         <br />
//       </h2>
//       {desc ? <p>{desc}</p> : null}
//     </div>
//   );

//   return (
//     <>
//       <div className="select_parent mb-8">
//         <button onClick={() => setChartView(false)} className="btn w-auto">
//           Card View
//         </button>
//         {/* <button
//           onClick={() => {
//             function downloadURI(uri, name) {
//               var link = document.createElement("a");
//               link.style.display = "none";
//               link.download = name;
//               link.href = uri;
//               link.target = "_blank";
//               document.body.appendChild(link);
//               link.click();
//               document.body.removeChild(link);
//             }
//             let chartHeight = "620";
//             let chartWidth = "1220";
//             let elm = document.createElement("div");
//             elm.innerHTML = document.getElementById("playrate")?.innerHTML;
//             elm
//               .getElementsByClassName("recharts-responsive-container")[0]
//               .setAttribute("width", chartWidth);
//             elm
//               .getElementsByClassName("recharts-responsive-container")[0]
//               .setAttribute("height", chartHeight);
//             elm
//               .getElementsByClassName("recharts-responsive-container")[0]
//               .setAttribute(
//                 "style",
//                 `width: ${chartWidth}; height: ${chartHeight};`
//               );
//             elm
//               .getElementsByClassName("recharts-wrapper")[0]
//               .setAttribute(
//                 "style",
//                 `position: relative; width: ${chartWidth}; height: ${chartHeight}`
//               );
//             elm
//               .getElementsByClassName("recharts-surface")[0]
//               .setAttribute("width", chartWidth);
//             elm
//               .getElementsByClassName("recharts-surface")[0]
//               .setAttribute("height", chartHeight);
//             elm
//               .getElementsByClassName("recharts-surface")[0]
//               .setAttribute("viewBox", `0 0 ${chartWidth} ${chartHeight}`);
//             let wrapper = document.createElement("div");
//             let bg = document.createElement("img");
//             bg.setAttribute("style", `
//             position: fixed;
//   top: 0px;
//   z-index: -9999;
//   height: 900px;
//   transform: scaleX(1.05) scaleY(1.05);
//   -webkit-user-select: none;
//   -moz-user-select: none;
//   user-select: none;
//   background-size: cover;
//   background-attachment: fixed;
//   background-position: center;
//   background-repeat: no-repeat;
//   filter: 5px;
//   -webkit-user-drag: none;`)
//   bg.src = require("helper/constants/base64").bgImage
//             let innerWrapper = document.createElement("div");
//             innerWrapper.append(elm);
//             innerWrapper.setAttribute(
//               "style",
//               `display: grid;
//             height: auto;
//             min-height: 100%;
//             width: 100%;
//             overflow: hidden;
//             background: rgba(0, 0, 0, 0.6);`
//             );
//             let footer = document.createElement("footer")
//             footer.innerHTML = `
//               <div style="font-family: Coda-64; position: absolute; text-align: center; color: rgb(255, 203, 119); font-weight: bold;">
//               <h2 style="font-size: 2.25rem; line-height: 2.5rem;">
//               Chart made by StatHalla
//               </h2>
//               </div>
            
//             `
//             innerWrapper.append(footer)
//             wrapper.append(innerWrapper);
//             wrapper.append(bg);
//             console.log(wrapper)

//             domtoimage
//               .toPng(wrapper, {
//                 width: 1200,
//                 height: 630,
//               })
//               .then(function (dataUrl:string) {
//                 console.log(dataUrl);
//                 // downloadURI(dataUrl, "chart.png")
//               })
//               .catch(function (error) {
//                 console.error("oops, something went wrong!", error);
//               });
//           }}
//           className="btn w-auto"
//         >
//           Export png
//         </button> */}
//       </div>
//       <div id="playrate">
//         <Title>Highest Playrate</Title>
//         <ResponsiveContainer width="100%" aspect={3}>
//           <BarChart
//             width={"100%"}
//             height={"100%"}
//             barCategoryGap={2}
//             data={playrateSortedLegends}
//           >
//             <CartesianGrid strokeDasharray="3 3" />
//             <XAxis
//               hide
//               // tick={false}
//               dataKey={({ id }: LegendStats) => getLegendById(id)?.bio_name}
//               stroke="white"
//             />
//             <YAxis
//               style={{
//                 fontFamily: "Coda-64",
//               }}
//               stroke="white"
//               tickFormatter={(value) => value + "%"}
//             />
//             <Tooltip
//               itemStyle={{
//                 color: "white",
//               }}
//               formatter={(value: string) => value + "%"}
//             />

//             <Bar
//               name="Playrate"
//               dataKey="playrate"
//               label={{
//                 position: "inside",
//                 fontFamily: "Coda-64",
//                 fill: "hsla(360, 0%, 100%, 1)",
//                 angle: 270,
//                 offset: 22,
//                 fontSize: 12,
//                 formatter: (value: string) => value + "%",
//               }}
//             >
//               {playrateSortedLegends.map((l: LegendStats, i: number) => (
//                 <Cell
//                   key={`playrate-cell-${i}`}
//                   radius={2}
//                   // fill={`rgba(${legends_colors[l.id.toString()]}, 0.8)`}
//                   fill={!(i % 2 === 0) ? "#FE6D73" : "#3BCDBE"}
//                 />
//               ))}
//             </Bar>
//           </BarChart>
//         </ResponsiveContainer>
//       </div>
//       <br />
//       <Title>Highest Winrate</Title>
//       <ResponsiveContainer width="100%" aspect={3}>
//         <BarChart
//           style={{
//             fontFamily: "Coda-64",
//           }}
//           width={"100%"}
//           height={"100%"}
//           barCategoryGap={2}
//           data={winrateSortedLegends}
//         >
//           <CartesianGrid strokeDasharray="3 3" />
//           <XAxis
//             hide
//             tick={false}
//             dataKey={({ id }: LegendStats) => getLegendById(id)?.bio_name}
//             stroke="white"
//           />
//           <YAxis stroke="white" tickFormatter={(value) => value + "%"} />
//           <Tooltip
//             itemStyle={{
//               color: "white",
//             }}
//             formatter={(value: string) => value + "%"}
//           />

//           <Bar
//             name="Winrate"
//             dataKey="winrate"
//             label={{
//               position: "inside",
//               fontFamily: "Coda-64",
//               fill: "hsla(360, 0%, 100%, 1)",
//               width: "100px",
//               angle: 270,
//               offset: 22,
//               fontSize: 12,
//               formatter: (value: string) => value + "%",
//             }}
//           >
//             {winrateSortedLegends.map((l: LegendStats, i: number) => (
//               <Cell
//                 key={`winrate-cell-${i}`}
//                 radius={2}
//                 // fill={`rgba(${legends_colors[l.id.toString()]}, 0.8)`}
//                 fill={!(i % 2 === 0) ? "#FE6D73" : "#3BCDBE"}
//               />
//             ))}
//           </Bar>
//         </BarChart>
//       </ResponsiveContainer>
//       <Title
//         desc={"Lower matchtime means matches end faster than other legends"}
//       >
//         Highest Matchtime(Average)
//       </Title>
//       <ResponsiveContainer width="100%" aspect={3}>
//         <BarChart
//           style={{
//             fontFamily: "Coda-64",
//           }}
//           width={"100%"}
//           height={"100%"}
//           barCategoryGap={2}
//           data={matchtimeSortedLegends}
//         >
//           <CartesianGrid strokeDasharray="3 3" />
//           <XAxis
//             hide
//             tick={false}
//             dataKey={({ id }: LegendStats) => getLegendById(id)?.bio_name}
//             stroke="white"
//           />
//           <YAxis stroke="white" tickFormatter={(value) => value + "s"} />
//           <Tooltip
//             itemStyle={{
//               color: "white",
//             }}
//             formatter={(value: string) => value + "s"}
//           />

//           <Bar
//             name="Matchtime"
//             dataKey="matchtime"
//             label={{
//               position: "inside",
//               fontFamily: "Coda-64",
//               fill: "hsla(360, 0%, 100%, 1)",
//               width: "100px",
//               angle: 270,
//               offset: 22,
//               fontSize: 12,
//               formatter: (value: string) => value + "s",
//             }}
//           >
//             {matchtimeSortedLegends.map((l: LegendStats, i: number) => (
//               <Cell
//                 key={`matchtime-cell-${i}`}
//                 radius={2}
//                 // fill={`rgba(${legends_colors[l.id.toString()]}, 0.8)`}
//                 fill={!(i % 2 === 0) ? "#FE6D73" : "#3BCDBE"}
//               />
//             ))}
//           </Bar>
//         </BarChart>
//       </ResponsiveContainer>
//       <Title>Most KOs (Average)</Title>
//       <ResponsiveContainer width="100%" aspect={3}>
//         <BarChart
//           style={{
//             fontFamily: "Coda-64",
//           }}
//           width={"100%"}
//           height={"100%"}
//           barCategoryGap={2}
//           data={kosSortedLegends}
//         >
//           <CartesianGrid strokeDasharray="3 3" />
//           <XAxis
//             hide
//             tick={false}
//             dataKey={({ id }: LegendStats) => getLegendById(id)?.bio_name}
//             stroke="white"
//           />
//           <YAxis stroke="white" tickFormatter={(value) => value} />
//           <Tooltip
//             itemStyle={{
//               color: "white",
//             }}
//             formatter={(value: string) => value}
//           />

//           <Bar
//             name="KOs"
//             dataKey="kos"
//             label={{
//               position: "inside",
//               fontFamily: "Coda-64",
//               fill: "hsla(360, 0%, 100%, 1)",
//               width: "100px",
//               angle: 270,
//               offset: 15,
//               fontSize: 12,
//               formatter: (value: string) => value,
//             }}
//           >
//             {kosSortedLegends.map((l: LegendStats, i: number) => (
//               <Cell
//                 key={`kos-cell-${i}`}
//                 radius={2}
//                 // fill={`rgba(${legends_colors[l.id.toString()]}, 0.8)`}
//                 fill={!(i % 2 === 0) ? "#FE6D73" : "#3BCDBE"}
//               />
//             ))}
//           </Bar>
//         </BarChart>
//       </ResponsiveContainer>
//       <Title>Most Damage Dealt (Average)</Title>
//       <ResponsiveContainer width="100%" aspect={3}>
//         <BarChart
//           style={{
//             fontFamily: "Coda-64",
//           }}
//           width={"100%"}
//           height={"100%"}
//           barCategoryGap={2}
//           data={dmgDealtSortedLegends}
//         >
//           <CartesianGrid strokeDasharray="3 3" />
//           <XAxis
//             hide
//             tick={false}
//             dataKey={({ id }: LegendStats) => getLegendById(id)?.bio_name}
//             stroke="white"
//           />
//           <YAxis stroke="white" tickFormatter={(value) => value} />
//           <Tooltip
//             itemStyle={{
//               color: "white",
//             }}
//             formatter={(value: string) => value}
//           />

//           <Bar
//             name="Damage Dealt"
//             dataKey="damagedealt"
//             label={{
//               position: "inside",
//               fontFamily: "Coda-64",
//               fill: "hsla(360, 0%, 100%, 1)",
//               width: "100px",
//               angle: 270,
//               offset: 20,
//               fontSize: 12,
//               formatter: (value: string) => value,
//             }}
//           >
//             {dmgDealtSortedLegends.map((l: LegendStats, i: number) => (
//               <Cell
//                 key={`dmg-cell-${i}`}
//                 radius={2}
//                 // fill={`rgba(${legends_colors[l.id.toString()]}, 0.8)`}
//                 fill={!(i % 2 === 0) ? "#FE6D73" : "#3BCDBE"}
//               />
//             ))}
//           </Bar>
//         </BarChart>
//       </ResponsiveContainer>
//       <Title desc={"Lower is better"}>Least Damage Taken (Average)</Title>
//       <ResponsiveContainer width="100%" aspect={3}>
//         <BarChart
//           style={{
//             fontFamily: "Coda-64",
//           }}
//           width={"100%"}
//           height={"100%"}
//           barCategoryGap={2}
//           data={dmgTakenSortedLegends}
//         >
//           <CartesianGrid strokeDasharray="3 3" />
//           <XAxis
//             hide
//             tick={false}
//             dataKey={({ id }: LegendStats) => getLegendById(id)?.bio_name}
//             stroke="white"
//           />
//           <YAxis stroke="white" tickFormatter={(value) => value} />
//           <Tooltip
//             itemStyle={{
//               color: "white",
//             }}
//             formatter={(value: string) => value}
//           />

//           <Bar
//             name="Damage Taken"
//             dataKey="damagetaken"
//             label={{
//               position: "inside",
//               fontFamily: "Coda-64",
//               fill: "hsla(360, 0%, 100%, 1)",
//               width: "100px",
//               angle: 270,
//               offset: 20,
//               fontSize: 12,
//               formatter: (value: string) => value,
//             }}
//           >
//             {dmgTakenSortedLegends.map((l: LegendStats, i: number) => (
//               <Cell
//                 key={`dmg-taken-cell-${i}`}
//                 radius={2}
//                 // fill={`rgba(${legends_colors[l.id.toString()]}, 0.8)`}
//                 fill={!(i % 2 === 0) ? "#FE6D73" : "#3BCDBE"}
//               />
//             ))}
//           </Bar>
//         </BarChart>
//       </ResponsiveContainer>
//     </>
//   );
// };

async function getLegendStats() {
  let data: AxiosResponse = await axios.get<AxiosResponse>(
    `${process.env.DOMAIN}/api/stats/legends`,
    {
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    }
  );
  let stats: Array<LegendStats> = JSON.parse(JSON.stringify(data.data));
  return stats;
}
export const getStaticProps: GetStaticProps = async (context) => {
  try {
    // let leaderboard: AxiosResponse = await axios.get<AxiosResponse>(`${process.env.DOMAIN}/api/rankings/1v1/1`, {
    //   headers: {
    //     "Content-Type": "application/json",
    //     "Accept": "application/json",
    //   },
    // })
    const queryClient = new QueryClient();
    await queryClient.prefetchQuery([`legend-stats`], getLegendStats, {
      staleTime: 60 * 19 * 1000,
      cacheTime: 60 * 19 * 1000,
    });

    return {
      props: {
        dehydratedState: dehydrate(queryClient),
      },
      // Re-fetches the data every {time} seconds
      // 20 minutes
      revalidate: 60 * 20,
    };
  } catch (e) {
    console.log(e);
    return {
      props: {
        error: !!e,
      },
      revalidate: 60,
    };
  }
};

interface pageProps {
  stats: Array<LegendStats>;
}

export default LegendStatsPage;
