import { CloudDownloadOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import { useTranslation } from 'next-i18next';
import { useQuery } from '@tanstack/react-query';
import { errorMessageFormatter } from '@/utils';
import { toast } from 'react-toastify';
import { AxiosErrorResponse, StudyGroup, StudyGroupMemberTaskComment } from '@/types';
import { getMemberTaskComments } from '@/services/study-group';
import { useState } from 'react';
import ExcelJS from 'exceljs';
import { dateTimeTransformer, dateTransformer } from '@/utils/timeTransformer';

interface ExportDataProps {
    query: StudyGroup;
}

const ExportData: React.FC<ExportDataProps> = ({ query }) => {
    const { t } = useTranslation(['study-group', 'layout', 'common', 'messages']);
    const [memberName, setMemberName] = useState<string>('');

    // Get Task Comments Query
    const { data, refetch } = useQuery({
        queryKey: ['task', 'comments', query],
        queryFn: async () => {
            const response = await getMemberTaskComments(query);
            return response.data;
        },
        onSuccess: (data: StudyGroupMemberTaskComment[]) => {
            setMemberName(data?.[0]?.member?.fullName);
        },
        onError: (error: AxiosErrorResponse & Error) => {
            toast.error(t(errorMessageFormatter(error)));
        },
    });

    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('Study Group Task Comments');

    // Columns
    worksheet.columns = [
        { header: 'Study Group', key: 'studyGroup', width: 20 },
        { header: 'Task Date', key: 'taskDate', width: 20 },
        { header: 'Comment', key: 'comment', width: 40 },
        { header: 'Created At', key: 'createdAt', width: 20 },
    ];

    // Add Row Style
    worksheet.getRow(1).font = { bold: true };
    worksheet.getRow(1).alignment = { horizontal: 'center' };
    worksheet.getRow(1).fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFA9A9A9' },
    };

    // Add Data Rows
    data?.map((comment: StudyGroupMemberTaskComment) => {
        const strippedComment = comment.comment.replace(/(<([^>]+)>)/gi, '');

        worksheet.addRow({
            studyGroup: comment.studyGroupTask?.studyGroup?.name,
            taskDate: dateTransformer(comment.studyGroupTask?.taskDate),
            comment: strippedComment,
            createdAt: dateTimeTransformer(comment.createdAt),
        });
    });

    const generateExcelHandler = async () => {
        // Generate the Excel file
        await workbook.xlsx.writeBuffer().then((buffer: any) => {
            const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.href = url;
            link.setAttribute('download', `${memberName}_studyGroupTaskComments.xlsx`);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });
    };

    const exportToCsvHandler = () => {
        refetch();
        generateExcelHandler();
    };

    return (
        <Button type="primary" icon={<CloudDownloadOutlined />} onClick={exportToCsvHandler}>
            {t('export-comments')}
        </Button>
    );
};

export default ExportData;
