import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuGroup,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
    IconCloudDownload,
    IconCopy,
    IconFileTypeCsv,
    IconFileTypeXls,
} from '@tabler/icons-react';
import { CSVLink } from 'react-csv';

import { show_toast } from '@/helper_files/toast';
import { useClipboard } from '@/hooks/useClipboard';
import ExcelJS from 'exceljs';
import saveAs from 'file-saver';

function AsyncExportFile({ columnOrder, data, fileName, hidden }) {
    const { copyToClipboard } = useClipboard();

    const filteredColumn = columnOrder
        .filter(d => typeof d?.columnDef?.header === 'string')
        .filter(d => !['actions', 'sl', 'select'].includes(d?.columnDef?.id));

    const columns = filteredColumn.map(
        (d, i) => d?.columnDef?.header ?? 'Column ' + (i + 1),
    );

    // Convert data to tab-separated string
    const dataToCopy = () => {
        if (data.length > 0) {
            // Get headers from the first row
            let copyData = `${columns.join('\t')}\n`;

            // take the field match with filterColumn.columnDef.id with d[id]
            // Extract matching values by columnDef.id
            const filteredData = data.map(row => {
                const newRow = {};
                columnOrder.forEach(col => {
                    const key = col.columnDef.id;
                    if (row.hasOwnProperty(key)) {
                        newRow[key] = row[key];
                    }
                });
                return newRow;
            });

            // Add data rows
            filteredData.forEach(row => {
                copyData += `${Object.values(row).join('\t')}\n`;
            });

            return copyData;
        }
        return '';
    };

    const copyData = async () => {
        // format data before copying to clipboard
        const copyDataAll = dataToCopy();

        if (copyDataAll) {
            const clipboardData = new Blob([copyDataAll], {
                type: 'text/plain',
            });

            const result = await copyToClipboard({
                'text/plain': clipboardData,
            });

            if (result.success) {
                show_toast('success', 'Copied data to clipboard');
            } else {
                show_toast('error', 'Failed to copy data to clipboard');
            }
        } else {
            show_toast('error', 'No data to copy');
        }
    };

    // Excel export function using ExcelJS
    const handleExportClick = async () => {
        // Create a new workbook and worksheet
        const workbook = new ExcelJS.Workbook();
        const worksheet = workbook.addWorksheet('Sheet1');

        // Get column headers from data keys
        const columnHeaders = columnOrder
            .filter(col => col.id !== 'actions')
            .map(col => ({
                header: col?.columnDef.header,
                key: col.id,
            }));

        // Add the column headers to the worksheet
        worksheet.columns = columnHeaders;

        // Add the data rows to the worksheet
        data.forEach(row => {
            worksheet.addRow(row);
        });

        // Set custom styles (optional)
        worksheet.getRow(1).font = { bold: true }; // Bold the header row

        // Create the Excel file as a blob and trigger download
        const buffer = await workbook.xlsx.writeBuffer();
        const blob = new Blob([buffer], { type: 'application/octet-stream' });

        // Trigger the download
        saveAs(blob, `${fileName}.xlsx`);
    };

    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild className={hidden ? 'hidden' : ''}>
                <Button
                    variant="secondary"
                    disabled={data?.length <= 0}
                    className="gap-2">
                    <IconCloudDownload size={20} className="text-base-400" />
                    <span className="md:flex hidden">Export</span>
                </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="start" className="w-full">
                <DropdownMenuGroup>
                    {/* <CopyToClipboard text={handleCopy} onCopy={handleCopy}> */}
                    <DropdownMenuItem className="cursor-pointer">
                        <button
                            onClick={copyData}
                            type="button"
                            className="flex items-center gap-1
                            text-base-400">
                            <IconCopy size={18} />
                            <span>Copy</span>
                        </button>
                    </DropdownMenuItem>
                    {/* </CopyToClipboard> */}
                    <CSVLink data={data} filename={fileName}>
                        <DropdownMenuItem className="flex cursor-pointer items-center gap-1 text-base-400">
                            <IconFileTypeCsv
                                className="text-base-400"
                                size={18}
                            />
                            <span>Csv</span>
                        </DropdownMenuItem>
                    </CSVLink>
                    <DropdownMenuItem
                        onClick={handleExportClick}
                        className="flex cursor-pointer items-center gap-1 text-base-400">
                        <IconFileTypeXls className="text-base-400" size={18} />
                        <span>Xlsx</span>
                    </DropdownMenuItem>
                    {/* <DropdownMenuItem
                        onClick={handleExportClick}
                        className="flex cursor-pointer items-center gap-1 text-base-400">
                        <IconFileTypePdf className="text-base-400" size={18} />
                        <span>excel</span>
                    </DropdownMenuItem> */}
                </DropdownMenuGroup>
            </DropdownMenuContent>
        </DropdownMenu>
    );
}

export default AsyncExportFile;
