import { DataTable } from "~/components/custom_ui/data-table";
import type {
  PinnedFiltro,
  SearchFiltro,
} from "~/components/custom_ui/dataTable-toolbar";
import { DataTableColumnHeader } from "~/components/custom_ui/dataTable-header";
import type { ColumnDef } from "@tanstack/react-table";
import { CircleCheck, ExternalLink } from "lucide-react";
import PaymentStatusEnum from "~/schemas/public/PaymentStatusEnum";
import { Button } from "~/components/ui/button";
import type { OrdiniWPagamenti } from "~/server/controllers/ordini.controller";
import OrderTypeEnum from "~/schemas/public/OrderTypeEnum";
import type { UsersId } from "~/schemas/public/Users";
import { OrdiniModal } from "~/components/area-riservata/ordini";
import type { OrdiniOrdineId } from "~/schemas/public/Ordini";
import Link from "next/link";
import { useState } from "react";

type PaymentsTableProps = {
  data: OrdiniWPagamenti[];
  isAdmin: boolean;
  userId?: UsersId;
};

export const OrdiniTable = ({ data, isAdmin, userId }: PaymentsTableProps) => {
  const tabledata = data.map((row) => {
    return {
      id: row.ordine_id,
      username: row.username,
      userId: row.userid,
      tipo: row.type,
      packid: row.packid,
      isActive: row.isActive,
      created_at: row.created_at,
      isPaid: row.pagamenti.some(
        (p) => p.paymentstatus === PaymentStatusEnum.success,
      ),
      actions: "Azioni",
    };
  });

  const columns_titles = {
    username: "Utente",
    created_at: "Creato il",
    tipo: "Tipo",
    packid: "ID Pacchetto",
    isPaid: "Pagato",
    actions: "Azioni",
  };
  const isPaidOptions = [
    { value: "true", label: "Pagato" },
    { value: "false", label: "Non pagato" },
  ];

  const type_options = [
    { value: OrderTypeEnum.Acconto, label: "Acconto" },
    { value: OrderTypeEnum.Saldo, label: "Saldo" },
    { value: OrderTypeEnum.Consulenza, label: "Consulenza" },
    { value: OrderTypeEnum.Altro, label: "Altro" },
  ];

  const [modalOpen, setModalOpen] = useState(false);
  const [selectedOrdine, setSelectedOrdine] = useState<OrdiniOrdineId | null>(
    null,
  );

  type Column = (typeof tabledata)[number];

  const columns: ColumnDef<Column>[] = [
    {
      header: ({ column }) => (
        <DataTableColumnHeader
          column={column}
          title={columns_titles.username}
        />
      ),
      accessorKey: "username",
      enableHiding: false,
      cell: ({ row }) => {
        if (isAdmin) {
          return (
            <Link
              aria-label="Visualizza Utente"
              href={`/area-riservata/admin/user-view/ricerca/${row.original.userId}`}
            >
              <Button size="sm">{row.original.username}</Button>
            </Link>
          );
        }
        return <span>{row.original.username}</span>;
      },
    },
    {
      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.tipo} />
      ),
      accessorKey: "tipo",
      cell: ({ row }) => {
        return row.original.tipo.toString();
      },
      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.packid} />
      ),
      accessorKey: "packid",
    },
    {
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={columns_titles.isPaid} />
      ),
      accessorKey: "isPaid",

      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));
      },
      cell: ({ row }) => {
        const isPaid = row.original.isPaid;
        const isActive = row.original.isActive;
        if (isActive) {
          return (
            <span className="inline-flex items-center gap-1 text-green-500">
              <CircleCheck className="size-5" />
              {isPaid ? "Pagato" : "Attivato da Admin"}
            </span>
          );
        }
        if (isPaid) {
          return (
            <span className="inline-flex items-center gap-1 text-green-500">
              <CircleCheck className="size-5" />
              Pagato
            </span>
          );
        } else {
          return (
            <span className="inline-flex items-center gap-1 text-red-500">
              <CircleCheck className="size-5" />
              Non pagato
            </span>
          );
        }
      },
    },

    {
      id: "actions",
      enableHiding: false,
      cell: ({ row }) => {
        return (
          <Button
            aria-label="Apri Dettagli Ordine"
            variant="outline"
            size="sm"
            onClick={() => {
              setSelectedOrdine(row.original.id);
              setModalOpen(true);
            }}
            className="flex items-center gap-2"
          >
            <ExternalLink className="size-6" />
            Apri Dettagli
          </Button>
        );
      },
    },
  ];

  const searchFiltro: SearchFiltro =
    isAdmin && !userId
      ? {
          columnName: "username",
          placeholder: "Cerca utente...",
        }
      : {
          columnName: "packid",
          placeholder: "Cerca pagamento...",
        };

  const pinnedFiltri: PinnedFiltro[] = [
    {
      columnName: "isPaid",
      title: "Stato Pagamento",

      options: isPaidOptions,
    },
    {
      columnName: "tipo",
      title: "Tipo Ordine",
      options: type_options,
    },
  ];

  return (
    <div className="mx-auto w-full py-10">
      <DataTable
        columns={columns}
        data={tabledata}
        pinnedFiltri={pinnedFiltri}
        searchColumn={searchFiltro}
        columns_titles={columns_titles}
        defaultSort={[{ desc: true, id: "created_at" }]}
        defaultColumnVisibility={{
          username: isAdmin && !userId,
          tipo: true,
          packid: true,
          status: true,
          amount: true,
          paid_at: true,
          actions: true,
        }}
      />
      {selectedOrdine && (
        <OrdiniModal
          ordineId={selectedOrdine}
          isAdmin={isAdmin}
          setModalOpen={setModalOpen}
          open={modalOpen}
          userId={userId}
        />
      )}
    </div>
  );
};
