"use client"

import { icons } from "#/assets/icons"
import Statistics from "#/components/stats"
import Table from "#/components/table/table"
import { Company } from "#/types"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { ColumnDef } from "@tanstack/react-table"
import axios from "axios"
import { useSession } from "next-auth/react"
import Image from "next/image"


export default function HomePage () {

  const {data: session, status} = useSession()
  const queryClient = useQueryClient()

  console.log("Session = ", session)

  const { data: companies, refetch, isLoading} = useQuery({
    enabled: status === 'authenticated',
    queryKey: ["companies"],
    queryFn: async () => {
        try {
            const response = await axios.get(
                'https://private-docs-api.intside.co/companies', {
                    headers: {
                        'Authorization': `Bearer ${session?.user.access_token}`
                    }
                }
            )

            if(response.data) {
                return response.data.data as Company[]
            }  
        } catch (error) {
            console.error(error)
        }
    }
  })

  const { mutate, isPending } = useMutation({
    mutationFn: async (id: string) => {
      try {
        const response = await axios.delete(
          `https://private-docs-api.intside.co/companies/${id}/`, {
            headers: {
                'Authorization': `Bearer ${session?.user.access_token}`
            }
        }
        )

        if(response.status === 200 || response.status === 201) {
          console.log('Suppresion réussie !')
        }
      } catch (error) {
        console.error(error)
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["companies"] })

      refetch()
    }
  })
  


  const columns: ColumnDef<Company>[] = [
  {
    accessorKey: "name",
    header: "Organisations",
  },
  // {
  //   accessorKey: "Utilisateurs",
  //   header: "Utilisateurs",
  // },
  {
    header: "Administrateurs",
    cell: ({ row }) => {
      const value = String(row.original.owner.first_name) + " " + String(row.original.owner.last_name)
      return(
        <p>{value}</p>
      )
    }
  },
  {
    accessorKey: "owner.email",
    header: "Adresse e-mail"
  },
  {
    accessorKey: "status",
    header: "Statut"
  },
  {
    id: "delete",
    cell: ({ cell }) => {
        const id = String(cell.row.original.id)
        return (
          <div className="relative p-2 cursor-pointer"
            onClick={() => { mutate(id) }}
          >
            <Image alt="" src={icons.trash} className="absolute right-2 top-[-50%] transform translate-middle-y hover:text-blue-500" />
          </div>
        )
    }
  }
]

  return(
    <div className="space-y-10">
      <Statistics />

      <Table 
        columns={columns} 
        data={companies || []} 
        pageSize={5}
      />
    </div>
  )
}