import { useQuery } from "@tanstack/react-query"
import wakapiApi from "../api/wakapi-api"
import { convertDateFriendly } from "../utils/convertDate"
import Scorecard from "../components/Scorecard"
import LanguagesChart from "../components/LanguagesChart"
import ProjectsChart from "../components/ProjectsChart"

const convertSeconds = (secs) => {
  return `${Math.floor(secs / 3600)}h ${Math.floor((secs % 3600) / 60)}m`
}

const CodeStats = () => {
  const { data, isLoading, error } = useQuery({
    queryKey: ["codestats"],
    queryFn: () =>
      wakapiApi.get(`summary?interval=week`).then((res) => res.data),
  })

  const grandTotal = data?.projects.reduce((acc, curr) => acc + curr.total, 0)
  const grandTotalFormatted = `${Math.floor(grandTotal / 3600)}h ${Math.floor((grandTotal % 3600) / 60)}m`
  const os = data?.operating_systems
  const osMetric = os ? (
    <div className="text-sm">
      {os[0]?.key}: {convertSeconds(os[0].total)}, {os[1]?.key}:{" "}
      {convertSeconds(os[1].total)}
    </div>
  ) : (
    "Error"
  )

  const personalProjects =
    data && data?.projects.filter((project) => !project.key.includes("gp-"))

  const personalProjectsSorted =
    personalProjects && personalProjects.sort((a, b) => b.total - a.total)

  const mainProject = personalProjects ? personalProjectsSorted[0].key : "Error"

  const languagesChartData = data?.languages
    .map((lang) => ({
      metric: lang.key,
      language: lang.key,
      hours: (lang.total / 3600).toFixed(1),
      percentage: (
        (lang.total / data.languages.reduce((sum, i) => sum + i.total, 0)) *
        100
      ).toFixed(1),
    }))
    .slice(0, 4)

  const projectsChartData =
    personalProjects &&
    personalProjects.map((proj) => ({
      metric: proj.key,
      project: proj.key,
      hours: (proj.total / 3600).toFixed(1),
      percentage: (
        (proj.total / personalProjects.reduce((sum, i) => sum + i.total, 0)) *
        100
      ).toFixed(1),
    }))

  return (
    <div className="container mx-auto p-4 grow">
      <div className="space-my-8">
        <section className="container">
          <div className="flex flex-col md:flex-row items-start md:items-center md:justify-between">
            <h2 className="text-2xl font-semibold mb-4 text-[#458588]! scanlined inline-block px-1">
              {`> code stats`}
            </h2>
            <div className="mb-4 text-sm text-muted">
              {convertDateFriendly(data?.from)} -{" "}
              {convertDateFriendly(data?.to)}
            </div>
          </div>
          {/* Score-cards */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <Scorecard
              title="time coding"
              metric={
                error ? "Error" : isLoading ? "Loading..." : grandTotalFormatted
              }
            />

            <Scorecard
              title="main project"
              metric={error ? "Error" : isLoading ? "Loading..." : mainProject}
            />

            <Scorecard
              title="OS"
              metric={error ? "Error" : isLoading ? "Loading..." : osMetric}
            />
          </div>
          <LanguagesChart chartData={languagesChartData} error={error} />
          <ProjectsChart chartData={projectsChartData} error={error} />
          <div className="text-sm text-center text-muted-foreground">
            Data sourced from my self-hosted{" "}
            <a
              href="https://wakapi.dev/"
              target="__blank"
              className="underline decoration-1 hover:text-primary/80 underline-offset-4 text-primary"
            >
              Wakapi
            </a>{" "}
            instance.
          </div>
        </section>
      </div>
    </div>
  )
}

export default CodeStats
