import { Dispatch, SetStateAction, useCallback } from "react";
import SelectOption from "../select-option";
import DashboardActionButton from "../dashboard-action-button";
import DownloadIcon from "@/shared/icons/dashboard/download-icon.svg";
import {
	downloadAsCSV,
	downloadAsPDF,
	getExportConfigFromColumns,
	TExportableData,
} from "@/shared/utils/export-utils";
import { ColumnDef } from "@tanstack/react-table";

type TDataExportToolbarProps<T extends TExportableData> = {
	selectedRow: T[];
	setSelectExportType: Dispatch<SetStateAction<string>>;
	selectExportType: string;
	columns: ColumnDef<T, any>[];
};

const DataExportToolbar = <T extends TExportableData>({
	selectedRow,
	setSelectExportType,
	selectExportType,
	columns,
}: TDataExportToolbarProps<T>) => {
	const exportConfig = getExportConfigFromColumns(
		columns,
		`installments-transactions-report-${new Date().toLocaleDateString()}`
	);

	const handleDownload = useCallback(() => {
		if (selectedRow.length === 0) return;

		if (selectExportType === "pdf") {
			downloadAsPDF(selectedRow, {
				...exportConfig,
				filename: exportConfig.filename + ".pdf",
			});
		} else {
			downloadAsCSV(selectedRow, {
				...exportConfig,
				filename: exportConfig.filename + ".csv",
			});
		}
	}, [selectExportType, selectedRow, exportConfig]);

	return (
		<div className='flex items-center gap-10'>
			<div className='flex items-center gap-4'>
				<p className='text-[14px] leading-[140%] text-[#333333]'>
					Export As
				</p>
				<SelectOption
					list={[
						{ value: "pdf", label: "PDF" },
						{ value: "csv", label: "CSV" },
					]}
					placeholder='Select export format'
					setValue={setSelectExportType}
					style='w-[200px] h-[48px]'
					defaultValue={selectExportType}
				/>
			</div>
			<DashboardActionButton
				activeBtn={selectedRow.length > 0}
				onClick={handleDownload}>
				<DownloadIcon className='h-[20px]! w-[20px]!' />
				<span>
					Download{" "}
					{selectedRow.length > 0 ? `(${selectedRow.length})` : ""}
				</span>
			</DashboardActionButton>
		</div>
	);
};

export default DataExportToolbar;
