"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);
  const [selectedId, setSelectedId] = useState<string | null>(null);

  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 } = 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: ({ row }) => {
      const id = String(row.original.id);
      return (
        <div className="relative p-2 cursor-pointer">
          <Modal
            open={selectedId === id}
            onOpenChange={(isOpen) => {
              if (!isOpen) {
                setSelectedId(null);
              }
            }}
            trigger={
              <div
                onClick={() => {
                  setSelectedId(id);
                }}
              >
                <Image
                  alt=""
                  src={icons.trash}
                  className="cursor-pointer responsive-icon"
                />
              </div>
            }
            title={
              <p className="font-bold text-3xl">
                Supprimer cette organisation
              </p>
            }
            content={
              <div>
                <p className="text-center">
                  Voulez-vous vraiment supprimer l'organisation <span className="font-bold">{row.original.name}</span> ?
                </p>

                <div className="flex justify-between w-full pt-6 r-gap-24">
                  <button
                    className="cta modal-cta cancel"
                    onClick={() => {
                      setSelectedId(null);
                    }}
                  >
                    Annuler
                  </button>
                  <button
                    className="cta modal-cta danger"
                    onClick={() => {
                      mutate(id);
                      setSelectedId(null);
                    }}
                  >
                    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>
  )
}