import { RecentEditsDataTable } from "@/components/RecentEditsDataTable"
import { useQuery } from "@tanstack/react-query"
import api from "../api/eolas-api"
import { Link } from "react-router"
import { ArrowUpDown } from "lucide-react"
import { Button } from "@/components/ui/button"
import { DataTable } from "@/components/DataTable"

const columns = [
   {
      accessorKey: "title",
      header: ({ column }) => {
         return (
            <Button
               variant="ghost"
               onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
            >
               Title
               <ArrowUpDown className="ml-2 h-4 w-4" />
            </Button>
         )
      },
      // header: "Title",
      cell: ({ cell, row }) => {
         return (
            <Link to={`entries/${row.original.title}`}>
               <span className="text-foreground underline-offset-3 underline hover:text-gray-700 dark:hover:text-green-300">
                  {row.original.title}
               </span>
            </Link>
         )
      },
   },
   {
      accessorKey: "date",
      header: "Date",
   },
   {
      accessorKey: "time",
      header: "Time",
   },
]

export default function RecentEdits() {
   const { data, isLoading } = useQuery({
      queryKey: ["entries_recent"],
      queryFn: () => api.get("/entries?limit=20&sort=date").then((res) => res.data),
   })

   console.log(data)
   const parsed = data?.data?.map((entry) => {
      const [date, time] = entry?.last_modified?.split(" ")
      return {
         title: entry.title.replace(/_/g, " "),
         date: new Date(date).toLocaleString("en-GB", {
            day: "numeric",
            month: "long",
            year: "numeric",
         }),
         time: time,
      }
   })

   return (
      <>
         <div className="border w-full">
            <div className="border-b py-2 px-4 lg:px-6 bg-sidebar">
               <h2 className="scroll-m-20 font-semibold">Recent edits</h2>
            </div>
            <div className="p-4 lg:p-6">
               <div className="container mx-auto py-2">
                  <DataTable columns={columns} data={parsed || []} loading={isLoading} />
               </div>
            </div>
         </div>
      </>
   )
}
