import type { ColumnDef } from "@tanstack/react-table";
import type { Users } from "~/schemas/public/Users";
import { DataTable } from "~/components/custom_ui/data-table";
import { DataTableColumnHeader } from "~/components/custom_ui/dataTable-header";
import type {
  SearchFiltro,
  PinnedFiltro,
} from "~/components/custom_ui/dataTable-toolbar";
import {
  Crown,
  Mail,
  MessagesSquare,
  MoreHorizontal,
  Paperclip,
  Search,
  ShoppingBag,
  Tickets,
  User,
  UserCog,
} from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "~/components/ui/dropdown-menu";
import { cn } from "~/lib/utils";
import { Button } from "~/components/ui/button";
import Link from "next/link";
import { api } from "~/utils/api";
import { useRouter } from "next/router";
import toast from "react-hot-toast";
import { UserAvatar } from "~/components/user_avatar";
type UserWChatInfo = Pick<
  Users,
  "id" | "username" | "email" | "isAdmin" | "isBlocked" | "created_at"
> & { chatid: string | null };

export const UsersTable = (props: { data: UserWChatInfo[] }) => {
  const router = useRouter();
  const { mutate: swap } = api.auth.swapUser.useMutation({
    onSuccess: async () => {
      toast.success("Utente cambiato con successo");
      await router.push("/area-riservata/dashboard");
      router.reload();
    },
  });

  const { data } = props;

  const tabledata = data.map((user) => {
    return {
      id: user.id,
      username: user.username,
      email: user.email,
      isAdmin: user.isAdmin ? "Admin" : "Utente",
      isBanned: user.isBlocked ? "Bloccato" : "Attivo",
      created_at: user.created_at,
      chatid: user.chatid,
      actions: "Azioni",
    };
  });

  const admin_options = [
    { label: "Admin", value: "Admin" },
    { label: "Utente", value: "Utente" },
  ];

  const columns_titles = {
    username: "User",
    email: "Email",
    isAdmin: "Ruolo",
    isBanned: "Status",
    created_at: "Creato il",
    actions: "Azioni",
  };
  type Column = (typeof tabledata)[number];

  const columns: ColumnDef<Column>[] = [
    {
      header: ({ column }) => (
        <DataTableColumnHeader
          column={column}
          title={columns_titles.username}
        />
      ),
      accessorKey: "username",
      enableHiding: false,
      cell: ({ row }) => {
        const user = row.original;
        return (
          <Link
            aria-label="Visualizza Utente"
            className="flex items-center gap-2"
            href={`/area-riservata/admin/user-view/edit-user/${user.id}`}
          >
            <UserAvatar
              className="size-8"
              username={user.username}
              userId={user.id}
            />
            <span className="text-sm font-semibold">{user.username}</span>
          </Link>
        );
      },
    },
    {
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={columns_titles.email} />
      ),
      accessorKey: "email",
    },
    {
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={columns_titles.isAdmin} />
      ),
      cell: ({ row }) => {
        const isadmin = admin_options.find(
          (status) => status.value === row.getValue("isAdmin"),
        );

        if (!isadmin) {
          return null;
        }

        return (
          <div
            className={cn(
              "flex w-[100px] items-center",
              isadmin.value === "Admin" && "text-green-500",
            )}
          >
            {isadmin.value === "Admin" && <Crown className="size-4" />}
            <span>{isadmin.label}</span>
          </div>
        );
      },
      filterFn: (row, id, value) => {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
        return value.includes(row.getValue(id));
      },

      accessorKey: "isAdmin",
    },
    {
      header: ({ column }) => (
        <DataTableColumnHeader
          column={column}
          title={columns_titles.isBanned}
        />
      ),
      accessorKey: "isBanned",
      filterFn: (row, id, value) => {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
        return value.includes(row.getValue(id));
      },
    },
    {
      header: ({ column }) => (
        <DataTableColumnHeader
          column={column}
          title={columns_titles.created_at}
        />
      ),
      accessorKey: "created_at",
      cell: ({ row }) => {
        const date = row.getValue("created_at");
        return new Date(date as Date).toLocaleDateString();
      },
      sortingFn: "datetime",
      enableHiding: false,
    },
    {
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={columns_titles.actions} />
      ),
      cell: ({ row }) => {
        const user = row.original;
        return (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" className="size-8 p-0">
                <span className="sr-only">Apri menu</span>
                <MoreHorizontal className="size-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuLabel>Azioni</DropdownMenuLabel>
              <DropdownMenuItem>
                <Link
                  aria-label="Visualizza Servizio"
                  className="flex w-full items-center gap-2"
                  href={`/area-riservata/admin/user-view/servizio/${user.id}`}
                >
                  <Tickets /> Servizio
                </Link>
              </DropdownMenuItem>
              <DropdownMenuItem>
                <Link
                  aria-label="Visualizza Ricerca"
                  className="flex w-full items-center gap-2"
                  href={`/area-riservata/admin/user-view/ricerca/${user.id}`}
                >
                  <Search className="text-neutral-600" /> Ricerca
                </Link>
              </DropdownMenuItem>
              <DropdownMenuItem>
                <Link
                  aria-label="Visualizza Comunicazioni"
                  className="flex w-full items-center gap-2"
                  href={`/area-riservata/admin/user-view/comunicazioni/${user.id}`}
                >
                  <Mail className="text-neutral-600" /> Comunicazioni
                </Link>
              </DropdownMenuItem>
              <DropdownMenuItem>
                <Link
                  aria-label="Visualizza Profilo"
                  className="flex w-full items-center gap-2"
                  href={`/area-riservata/admin/user-view/edit-user/${user.id}`}
                >
                  <UserCog className="text-neutral-600" /> Profilo
                </Link>
              </DropdownMenuItem>

              <DropdownMenuItem>
                <Link
                  aria-label="Visualizza Ordini"
                  className="flex w-full items-center gap-2"
                  href={`/area-riservata/admin/user-view/ordini/${user.id}`}
                >
                  <ShoppingBag className="text-neutral-600" /> Ordini
                </Link>
              </DropdownMenuItem>
              <DropdownMenuItem>
                <Link
                  aria-label="Visualizza Allegati"
                  className="flex w-full items-center gap-2"
                  href={`/area-riservata/admin/user-view/allegati/${user.id}`}
                >
                  <Paperclip className="text-neutral-600" /> Allegati
                </Link>
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem>
                <Link
                  aria-label="Visualizza Chat"
                  className={cn(
                    "flex w-full items-center gap-2 text-neutral-200",
                    user.chatid && "text-neutral-600",
                  )}
                  href={
                    user.chatid
                      ? {
                          pathname: "/area-riservata/admin/chats",
                          query: { chatId: user.chatid },
                        }
                      : "/area-riservata/admin/chats"
                  }
                >
                  <MessagesSquare /> Chat
                </Link>
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem>
                <button
                  aria-label="Login as User"
                  className="flex w-full items-center gap-2"
                  onClick={() =>
                    swap({
                      id: user.id,
                    })
                  }
                >
                  <User /> Login
                </button>
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        );
      },
      accessorKey: "actions",
      enableHiding: false,
      enableSorting: false,
    },
  ];
  const pinnedFiltri: PinnedFiltro[] = [
    {
      title: "Ruolo",
      columnName: "isAdmin",
      options: [
        { label: "Admin", value: "Admin" },
        { label: "Utente", value: "Utente" },
      ],
    },
    {
      title: "Status",
      columnName: "isBanned",
      options: [
        { label: "Bloccato", value: "Bloccato" },
        { label: "Attivo", value: "Attivo" },
      ],
    },
  ];
  const searchFiltro: SearchFiltro = {
    columnName: "username",
    placeholder: "Filtra utenti...",
  };
  return (
    <div className="mx-auto w-full px-2 py-10">
      <DataTable
        columns={columns}
        data={tabledata}
        pinnedFiltri={pinnedFiltri}
        searchColumn={searchFiltro}
        columns_titles={columns_titles}
        defaultSort={[{ desc: true, id: "created_at" }]}
      />
    </div>
  );
};
