import type { ColumnDef } from "@tanstack/react-table";
import { Circle, CircleCheck, ExternalLink } from "lucide-react";
import Link from "next/link";
import { useState } from "react";
import {
	AdminWrapperOrdiniModal,
	UserOrdiniModal,
} from "~/components/area-riservata/ordini";
import { DataTable } from "~/components/custom_ui/data-table";
import { DataTableColumnHeader } from "~/components/custom_ui/dataTable-header";
import type {
	PinnedFiltro,
	SearchFiltro,
} from "~/components/custom_ui/dataTable-toolbar";
import { Button } from "~/components/ui/button";
import { formatCurrency } from "~/lib/utils";
import OrderTypeEnum from "~/schemas/public/OrderTypeEnum";
import type { OrdiniOrdineId } from "~/schemas/public/Ordini";
import PaymentStatusEnum from "~/schemas/public/PaymentStatusEnum";
import type { UsersId } from "~/schemas/public/Users";
import type { Ordini_w_Utente } from "~/server/services/ordini.service";

type PaymentsTableProps = {
	data: Ordini_w_Utente[];
	isAdmin: boolean;
	userId?: UsersId;
	filter: OrdiniOrdineId | null;
};

const StatusMapping = (status: PaymentStatusEnum | null) => {
	switch (status) {
		case PaymentStatusEnum.success:
			return "Successo";
		case PaymentStatusEnum.processing:
			return "In lavorazione";
		case PaymentStatusEnum.failed:
			return "Errore";
		default:
			return "Non completato";
	}
};

export const OrdiniTable = ({
	data,
	isAdmin,
	userId,
	filter,
}: PaymentsTableProps) => {
	const tabledata = data.map((row) => {
		return {
			actions: "Azioni",
			created_at: row.created_at,
			id: row.ordine_id,
			status: row.isActive,
			payment_status: row.paymentstatus,
			importo: row.amount_cent,
			packid: row.packid,
			tipo: row.type,
			userId: row.userid,
			username: row.username,
		};
	});

	const columns_titles = {
		id: "ID Ordine",
		actions: "Azioni",
		created_at: "Creato il",
		importo: "Importo",
		status: "Status",
		payment_status: "Pagamento",
		packid: "ID Pacchetto",
		tipo: "Tipo",
		username: "Utente",
	};
	const statusOptions = [
		{ label: "Attivo", value: "true" },
		{ label: "Non attivo", value: "false" },
	];

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

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

	type Column = (typeof tabledata)[number];

	const columns: ColumnDef<Column>[] = [
		{
			accessorKey: "id",
			cell: () => null,
			enableHiding: false,
			header: () => null,
		},

		{
			accessorKey: "username",
			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>;
			},
			enableHiding: false,
			header: ({ column }) => (
				<DataTableColumnHeader
					column={column}
					title={columns_titles.username}
				/>
			),
		},
		{
			accessorKey: "created_at",
			cell: ({ row }) => {
				const date = row.getValue("created_at");
				return new Date(date as Date).toLocaleDateString();
			},
			enableHiding: false,
			header: ({ column }) => (
				<DataTableColumnHeader
					column={column}
					title={columns_titles.created_at}
				/>
			),
			sortingFn: "datetime",
		},
		{
			accessorKey: "tipo",
			cell: ({ row }) => {
				return row.original.tipo.toString();
			},
			filterFn: (row, id, value) => {
				return value.includes(row.getValue(id));
			},
			header: ({ column }) => (
				<DataTableColumnHeader column={column} title={columns_titles.tipo} />
			),
		},

		{
			accessorKey: "packid",
			header: ({ column }) => (
				<DataTableColumnHeader column={column} title={columns_titles.packid} />
			),
		},
		{
			accessorKey: "importo",
			cell: ({ row }) => {
				return <span>{formatCurrency(row.original.importo / 100)}</span>;
			},
			header: ({ column }) => (
				<DataTableColumnHeader column={column} title={columns_titles.importo} />
			),
			enableHiding: false,
			sortingFn: (a, b, id) => {
				const aValue = a.getValue(id) as number;
				const bValue = b.getValue(id) as number;
				return aValue - bValue;
			},
		},
		{
			accessorKey: "status",
			cell: ({ row }) => {
				if (!row.original.status) {
					return (
						<span className="inline-flex items-center gap-1">
							<Circle className="size-5" />
							Non attivo
						</span>
					);
				}
				return (
					<span className="inline-flex items-center gap-1 text-green-500">
						<CircleCheck className="size-5" />
						Attivo
					</span>
				);
			},

			filterFn: (row, id, value) => {
				return value.includes(row.getValue(id));
			},
			header: ({ column }) => (
				<DataTableColumnHeader column={column} title={columns_titles.status} />
			),
		},
		{
			accessorKey: "payment_status",
			cell: ({ row }) => {
				return <span>{StatusMapping(row.original.payment_status)}</span>;
			},

			filterFn: (row, id, value) => {
				return value.includes(row.getValue(id));
			},
			header: ({ column }) => (
				<DataTableColumnHeader
					column={column}
					title={columns_titles.payment_status}
				/>
			),
		},
		{
			cell: ({ row }) => {
				return (
					<Button
						aria-label="Apri Dettagli Ordine"
						onClick={() => {
							setSelectedOrdine(row.original.id);
						}}
						size="sm"
						variant="outline"
					>
						<ExternalLink className="size-5" />
					</Button>
				);
			},
			enableHiding: false,
			id: "actions",
		},
	];

	const searchFiltro: SearchFiltro = {
		columnName: "id",
		placeholder: "Cerca ordine...",
	};

	const pinnedFiltri: PinnedFiltro[] = [
		{
			columnName: "status",

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

	return (
		<div className="mx-auto w-full">
			<DataTable
				columns={columns}
				columns_titles={columns_titles}
				data={tabledata}
				defaultColumnVisibility={{
					actions: true,
					amount: true,
					packid: true,
					paid_at: true,
					status: true,
					tipo: true,
					username: isAdmin && !userId,
				}}
				defaultFilterState={
					filter ? [{ id: "id", value: filter.toString() }] : []
				}
				defaultSort={[{ desc: true, id: "created_at" }]}
				pinnedFiltri={pinnedFiltri}
				searchColumn={searchFiltro}
			/>
			{isAdmin ? (
				<AdminWrapperOrdiniModal
					ordineId={selectedOrdine}
					setSelected={setSelectedOrdine}
				/>
			) : (
				selectedOrdine && (
					<UserOrdiniModal
						ordineId={selectedOrdine}
						setSelected={setSelectedOrdine}
					/>
				)
			)}
		</div>
	);
};
