"use client";

import { useState } from "react";
import Image from "next/image";
import { useSession } from "next-auth/react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { ColumnDef } from "@tanstack/react-table";
import axios from "axios";
import { DropdownMenu } from "radix-ui";
import FloatingLabelInput from "#/components/floatingLabelInput";
import { Modal } from "#/components/modal";
import Table from "#/components/table/table";
import Form from "#/components/form/form";
import { icons } from "#/assets/icons";
import { companySchema } from "#/schema";
import { Admin, Company } from "#/types";
import Link from "next/link";


export default function Organizations() {
  const { data: session, status } = useSession();
  const [openModal, setOpenModal] = useState(false);
  const [openDeleteModal, setOpenDeleteModal] = useState(false);
  const [selectedAdminId, setSelectedAdminId] = useState<string | null>(null);

  const queryClient = useQueryClient();

  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 {
    data: users,
  } = useQuery({
    enabled: status === "authenticated",
    queryKey: ["organizations"],
    queryFn: async () => {
      try {
        const response = await axios.get(
          "https://private-docs-api.intside.co/users",
          {
            headers: { Authorization: `Bearer ${session?.user.access_token}` },
          }
        );
        return response.data.data.map((user: Admin) => ({
          id: user.id,
          name: `${user.first_name} ${user.last_name}`,
        }));
      } catch (error) {
        console.error(error);
        return [];
      }
    },
  });

  const createMutation = useMutation({
    mutationFn: async (data: {
      name: string;
      description: string;
      status: string;
      is_premium: string;
      owner: string;
    }) => {
      try {
        const response = await axios.post(
          "https://private-docs-api.intside.co/companies/",
          data,
          { headers: { Authorization: `Bearer ${session?.user.access_token}` } }
        );

        if (response.status === 200 || response.status === 201) {
          console.log("ajout réussie !");
          setOpenModal(false);
        }
      } catch (error) {
        console.error("Erreur lors de la création", error);
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["organizations"] });
      refetch();
    },
  });

  const deleteMutation = 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 !");
          setOpenDeleteModal(false);
        }
      } catch (error) {
        console.error("Erreur lors de la suppression", error);
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["organizations"] });
      refetch();
    },
  });

  const bulkDeleteMutation = useMutation({
    mutationFn: async (ids: string[]) => {
      try {
        const deletePromises = ids.map((id) =>
          axios.delete(`https://private-docs-api.intside.co/companies/${id}/`, {
            headers: { Authorization: `Bearer ${session?.user.access_token}` },
          })
        );
        await Promise.all(deletePromises);
      } catch (error) {
        console.error("Erreur lors de la suppression groupée", error);
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["organizations"] });
      refetch();
    },
  });

  const columns: ColumnDef<Company>[] = [
    {
      accessorKey: "name",
      header: "Organisations",
      cell: ({ row }) => {
        const company = row.original;
        return (
          <Link href={`/admin/organizations/${company.id}`}>
            <p className="text-blue-600 hover:underline">{company.name}</p>
          </Link>
        );
      },
    },
    {
      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" ? "font-medium w-[80px] h-[24px] bg-[#ECF9E8] text-[#49C91E]" :
                status === "inactive" ? "font-medium w-[80px] h-[24px] bg-[#E7EBF3] text-[#9FA8BC]" : 
                status === "pending" ? "font-medium w-[80px] h-[24px] bg-[#EAF7FC] text-[#30B2EA]" : 
                status === "blocked" ? "font-medium w-[80px] h-[24px] bg-[#FDEBE8] text-[#F33F19]" : 
                ""
              }
            `}
          >
            {
              status === "active" ? "Actif" : 
              status === "inactive" ? "Inactif" : 
              status === "pending" ? "En attente" : 
              status === "blocked" ? "Bloquée" : 
              ""
            }
          </p>
        )
      }
    },
    {
      id: "delete",
      cell: ({ row }) => {
        const company = row.original;
          return (
            <div className="flex justify-end p-2 space-x-2"
              // onClick={() => { mutate(id) }}
            >

              {/* Modal de suppression */}
                <Modal
                  open={openDeleteModal && selectedAdminId === company.id}
                  onOpenChange={(isOpen) => {
                    if (!isOpen) {
                      setSelectedAdminId(null);
                      setOpenDeleteModal(false);
                    }
                  }}
                  trigger={
                    <div
                      onClick={() => {
                        setSelectedAdminId(company.id);
                        setOpenDeleteModal(true);
                      }}
                    >
                      <Image
                        alt="Supprimer"
                        src={icons.trash}
                        className="cursor-pointer responsive-icon"
                      />
                    </div>
                  }
                  title="Supprimer une organisation"
                  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={() => {
                            setOpenDeleteModal(false);
                          }}
                        >
                          Annuler
                        </button>
                        <button
                    className="cta modal-cta danger"
                    onClick={() => {
                            deleteMutation.mutate(company.id);
                          }}
                        >
                          Supprimer
                        </button>
                      </div>
                    </div>
                  }
                />
            </div>  
          )
      }
    }
  ]

  return (
    <Table
      columns={columns}
      data={companies || []}
      pageSize={5}
      isDataLoading={isLoading}
      header={(table) => {
        const selectedIds = table
          .getRowModel()
          .rows.filter((row) => row.getIsSelected())
          .map((row) => row.original.id);

        return (
          <div className="grid grid-cols-1 lg:grid-cols-2 w-full space-y-3">
            <div className="flex items-center space-x-3">
              <input
                type="checkbox"
                checked={
                  table.getIsAllPageRowsSelected() ||
                  (table.getIsSomePageRowsSelected() && undefined)
                }
                onChange={(e) =>
                  table.toggleAllPageRowsSelected(e.target.checked)
                }
              />

              <DropdownMenu.Root>
                <DropdownMenu.Trigger asChild>
                  <p className="cta cancel flex gap-2">
                    Sélectionner une action
                    <Image src={icons.arrowDown} alt="arrow down" />
                  </p>
                </DropdownMenu.Trigger>

                <DropdownMenu.Portal>
                  <DropdownMenu.Content
                    className="min-w-[150px] shadow-sm bg-white rounded-md p-1 w-full"
                    sideOffset={0} side="bottom" align="end"
                  >
                    <DropdownMenu.Item
                      onClick={() => bulkDeleteMutation.mutate(selectedIds)}
                      className="p-2 text-[14px] cursor-pointer hover:bg-blue-100 hover:text-blue-500 rounded-md"
                    >
                      Supprimer
                    </DropdownMenu.Item>
                  </DropdownMenu.Content>
                </DropdownMenu.Portal>
              </DropdownMenu.Root>
            </div>

            <div className="flex justify-between lg:justify-end space-x-3">
              {/* Modal d'ajout */}
              <Modal
                title="Ajouter une organisation"
                open={openModal}
                onOpenChange={(isOpen) => {
                  if (!isOpen) {
                    setOpenModal(false);
                  }
                }}
                trigger={
                  <div
                    onClick={() => setOpenModal(true)}
                    className="cta"
                  >
                    Ajouter une organisation
                  </div>
                }
                content={
                  <Form
                    fields={[
                      {
                        name: "name",
                        label: "Nom de l'organisation",
                        type: "text",
                        placeholder: "Entrer le nom de l'organisation",
                      },
                      {
                        name: "description",
                        label: "Description",
                        type: "textarea",
                        placeholder: "Entrer la description de l'organisation",
                      },
                      {
                        name: "status",
                        label: "Statut",
                        type: "select",
                        options: [
                          { label: "Actif", value: "active" },
                          { label: "Inactif", value: "inactive" },
                          { label: "En attente", value: "pending" },
                          { label: "Bloqué", value: "blocked" },
                        ],
                      },
                      {
                        name: "owner",
                        label: "Administrateur",
                        type: "select",
                        options: users?.map((user: { id: string; name: string }) => ({
                          label: user.name,
                          value: user.id,
                        })) || [],
                      },
                    ]}
                    submit={createMutation.mutate} // Le type est maintenant compatible
                    schema={companySchema}
                    child={
                      <div className="flex justify-center">
                      <button
                        type="submit"
                        disabled={createMutation.isPending}
                        className={`${createMutation.isPending ? "btn-auth-loading" : "btn-auth"} cta modal-cta mt-4 cursor-pointer`}
                      >
                        {createMutation.isPending ? "En cours..." : "Ajouter une organisation"}
                      </button>
                      </div>
                    }
                  />
                }
              />

              <FloatingLabelInput
                name="search"
                placeholder="Effectuer une recherche"
                type="search"
                onChange={(value) => table.setGlobalFilter(value)}
                button={
                  <Image
                    alt="Filtrer"
                    src={icons.filterIcon}
                    className="cursor-pointer"
                  />
                }
              />
            </div>
          </div>
        );
      }}
    />
  );
}
