import dayjs from "dayjs";
import {
	ChevronLeft,
	ChevronRight,
	ChevronsLeft,
	ChevronsRight,
} from "lucide-react";
import { ComponentType } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "react-toastify";

import { Loading } from "@/contexts/loading/ui/Loading";
import { FileType, GetReportsResponseItem } from "@/contracts/client.schemas";
import { useCreateExport } from "@/contracts/exports";
import { useReportTitle } from "@/features/Reports/lib/useReportTitle";
import { saveFile } from "@/modules/reports/utils/file";
import { formatDateTimeWithoutSeconds } from "@/services/time.service";
import {
	ExcelIcon,
	Icon,
	Pagination,
	PaginationContent,
	PaginationEllipsis,
	PaginationItem,
	PaginationLink,
	PdfIcon,
	SortButton,
	ZipIcon,
} from "@/shared";
import { IconButton } from "@/shared/IconButton/ui/IconButton";

import { useReportFileName } from "../lib/useReportFileName";
import { useReportList } from "../lib/useReportList";

export const ReportTable = () => {
	const { t, i18n } = useTranslation("translation");
	const {
		isFirstEnabled,
		isPreviousEnabled,
		isNextEnabled,
		isLastEnabled,
		currentPage,
		paginationPages, // <--- Теперь используем этот единый массив
		toPage,
		toFirstPage,
		toPreviousPage,
		toNextPage,
		toLastPage,
		rows,
		isFetching,
		sorting,
		setSorting,
	} = useReportList();
	const { getTitle } = useReportTitle();
	const { mutateAsync: createExport, isPending: isExportPending } =
		useCreateExport();
	const { getFileName } = useReportFileName();

	const actions: {
		key: string;
		labelKey: "Pdf format" | "Excel format" | "Zip format";
		icon: ComponentType<Icon>;
		onClick: (row: GetReportsResponseItem) => void;
	}[] = [
		{
			key: "pdf",
			labelKey: "Pdf format",
			icon: PdfIcon,
			onClick: (row: GetReportsResponseItem) =>
				exportReport(row, FileType.Pdf),
		},
		{
			key: "excel",
			labelKey: "Excel format",
			icon: ExcelIcon,
			onClick: (row: GetReportsResponseItem) =>
				exportReport(row, FileType.Excel),
		},
		{
			key: "zip",
			labelKey: "Zip format",
			icon: ZipIcon,
			onClick: (row: GetReportsResponseItem) =>
				exportReport(row, FileType.Zip),
		},
	];

	async function exportReport(
		report: GetReportsResponseItem,
		fileType: FileType,
	) {
		try {
			const response = await createExport({
				data: {
					reportId: report.id,
					fileType: fileType,
					language: i18n.language,
					timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
				},
			});

			toast.success(t("Report downloaded successfully"));

			saveFile(
				response,
				getFileName(
					report.type,
					fileType,
					dayjs(report.createdAt).toDate(),
				),
			);
		} catch (error) {
			toast.error(t("Report download failed"));
			console.error(error);
		}
	}

	return (
		<div className="h-[calc(80vh)] rounded-[10px] overflow-hidden flex flex-col gap-[20px] bg-[var(--white)] shadow-[0_0_10px_0_rgba(0,0,0,0.1)] p-[20px]">
			{/* <div className="">
				<SearchBox
					onSearch={handleSearch}
					search={searchTerm}
					labelKey="Search"
				/>
			</div> */}

			<div className="flex justify-start items-center gap-2">
				<span>{t("Sorting: ")}</span>
				<SortButton
					label={t("by date")}
					direction={
						sorting === "byDateFront"
							? "asc"
							: sorting === "byDateBack"
								? "desc"
								: undefined
					}
					onClick={() => {
						setSorting(
							sorting === "byDateFront"
								? "byDateBack"
								: sorting === "byDateBack"
									? undefined
									: "byDateFront",
						);
					}}
				/>
				<SortButton
					label={t("alphabetically")}
					direction={
						sorting === "byNameFront"
							? "asc"
							: sorting === "byNameBack"
								? "desc"
								: undefined
					}
					onClick={() => {
						setSorting(
							sorting === "byNameFront"
								? "byNameBack"
								: sorting === "byNameBack"
									? undefined
									: "byNameFront",
						);
					}}
				/>
			</div>

			<div className="w-full overflow-y-auto grow">
				<div className="w-full flex flex-col gap-[10px]">
					{rows && rows.length > 0 ? (
						rows.map((row) => (
							<div
								key={row.id}
								className="bg-[var(--black-50)] hover:bg-[var(--black-100)] px-[20px] py-[5px] flex justify-between items-center rounded-[10px] gap-[20px]"
							>
								<div className="text-black-800 font-[Inter] text-[16px] font-normal">
									{formatDateTimeWithoutSeconds(
										dayjs(row.createdAt).toDate(),
									)}
								</div>
								<div className="grow text-black-950 font-[Inter] text-[16px] font-medium">
									{getTitle(row.type)}
								</div>
								<div className="text-right flex gap-2">
									{actions.map((action) => (
										<IconButton
											key={action.key}
											Icon={action.icon}
											titleKey={action.labelKey}
											color={"var(--black-500)"}
											hoverColor="var(--white)"
											className="hover:bg-[var(--primary-500)] hover:rounded-lg disabled:opacity-50"
											disabled={isExportPending}
											onClick={() => action.onClick(row)}
										/>
									))}
								</div>
							</div>
						))
					) : (
						<div>
							<div className="h-24 text-center">
								{t("Empty list")}
							</div>
						</div>
					)}
				</div>

				{isFetching && <Loading />}
			</div>

			<Pagination>
				<PaginationContent>
					<PaginationItem>
						<PaginationLink
							aria-disabled={!isFirstEnabled}
							onClick={() => toFirstPage()}
						>
							<ChevronsLeft size={20} />
						</PaginationLink>
					</PaginationItem>

					<PaginationItem>
						<PaginationLink
							aria-disabled={!isPreviousEnabled}
							onClick={() => toPreviousPage()}
						>
							<ChevronLeft size={20} />
						</PaginationLink>
					</PaginationItem>

					{/* Итерируемся по единому массиву paginationPages */}
					{paginationPages.map((item, index) => (
						<PaginationItem key={index}>
							{item === "ellipsis" ? (
								<PaginationEllipsis />
							) : (
								<PaginationLink
									isActive={item === currentPage}
									onClick={() => toPage(item as number)}
								>
									{(item as number) + 1}{" "}
									{/* Отображаем 1-based номер страницы */}
								</PaginationLink>
							)}
						</PaginationItem>
					))}

					<PaginationItem>
						<PaginationLink
							aria-disabled={!isNextEnabled}
							onClick={() => toNextPage()}
						>
							<ChevronRight size={20} />
						</PaginationLink>
					</PaginationItem>

					<PaginationItem>
						<PaginationLink
							aria-disabled={!isLastEnabled}
							onClick={() => toLastPage()}
						>
							<ChevronsRight size={20} />
						</PaginationLink>
					</PaginationItem>
				</PaginationContent>
			</Pagination>
		</div>
	);
};
