"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"
import { Modal } from "#/components/modal"
import { useState } from "react"

export default function HomePage () {

  const {data: session, status} = useSession()
  const queryClient = useQueryClient()
  const [open, setOpen] = useState(false);

  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 !')
          setOpen(false)
        }
      } catch (error) {
        console.error(error)
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["companies"] })

      refetch()
    }
  })
  


  const columns: ColumnDef<Company>[] = [
  {
    accessorKey: "name",
    header: "Organisations",
  },
  {
    accessorKey: "total_users",
    header: "Utilisateurs",
  },
  {
    header: "Administrateurs",
    cell: ({ row }) => {
      const value = String(row.original.owner.first_name) + " " + String(row.original.owner.last_name)
      const initials = String(row.original.owner.first_name[0]) + String(row.original.owner.last_name[0])
      return(
        <div className="flex space-x-2 items-center">
          <div className="flex items-center justify-center bg-[#DCDCFE] text-[#246BFD] w-10 h-10 rounded-full">
            {initials}
          </div>
          <p>{value}</p>
        </div>
      )
    }
  },
  {
    accessorKey: "owner.email",
    header: "Adresse e-mail"
  },
  {
    accessorKey: "status",
    header: "Statut",
    cell: ({ cell }) => {
      const status = String(cell.getValue())
      return (
        <p
          className={`rounded-full px-2 py-1 font-medium text-sm w-20 h-6 text-center
            ${ 
              status === "active" ? "bg-[#ECF9E8] text-[#49C91E]" :
              status === "inactive" ? "bg-[#E7EBF3] text-[#9FA8BC]" : 
              status === "pending" ? "bg-[#EAF7FC] text-[#30B2EA]" : 
              status === "blocked" ? "bg-[#FDEBE8] text-[#F33F19]" : 
              ""
            }
          `}
        >
          {
            status === "active" ? "Actif" : 
            status === "inactive" ? "Inactif" : 
            status === "pending" ? "En attente" : 
            status === "blocked" ? "Bloquée" : 
            ""
          }
        </p>
      )
    }
  },
  {
    id: "delete",
    cell: ({ cell }) => {
        const id = String(cell.row.original.id)
        return (
          <div className="relative p-2 cursor-pointer"
            // onClick={() => { mutate(id) }}
          >
            <Modal 
              open={open}
              onOpenChange={(isOpen)=>{
                if(!isOpen) {
                  setOpen(isOpen)
                }
              }}
              trigger={
                <div onClick={() => setOpen(true)}>
                  <Image alt="" src={icons.trash} className="absolute right-2 top-[-50%] transform translate-middle-y hover:text-blue-500" />
                </div>
              }
              title={
                <p className="font-bold text-3xl">Supprimer une organisation</p>
              }
              content={
                <div>
                  <p>Voulez-vous vraiment supprimer cette organisation ?</p>

                  <div className="grid grid-cols-2 gap-3 mt-3">
                    <button 
                      className="bg-blue-100 text-blue-600 py-2 px-4 text-lg rounded-full text-center hover:bg-blue-200"
                      onClick={() => { setOpen(false) }}
                      >
                      Annuler
                    </button>
                    <button 
                      className="bg-red-500 text-white py-2 px-4 text-lg rounded-full text-center hover:bg-red-600"
                      onClick={() => { 
                        mutate(id)
                        setOpen(false) 
                      }}
                    >
                      Supprimer
                    </button>
                  </div>
                </div>
              }
            />
          </div>  
        )
    }
  }
]

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

      <p className="font-bold text-xl">Dernières organisations actives</p>

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