import Filters, { FilterValues } from '../../components/Filters';
import { FC, useState } from 'react'
import Table from '../../components/Table';
import { ColumnType } from '../../components/types/TableTypes';
import { InfoCircle, Refresh2, Trash, RecoveryConvert } from 'iconsax-react';
import { RowActionItem } from '../../components/RowActionsDropdown';
import { useNavigate } from 'react-router-dom';
import { useEmptyTrash, useGetTrashMessages } from './hooks/useTrashData';
import { TrashMessage } from './types/TrashTypes';
import { formatDate } from '@/config/func';
import { useEmailActions } from '@/hooks/useEmailActions';
import Button from '@/components/Button';
import ModalConfrim from '@/components/ModalConfrim';
import { ErrorType } from '@/helpers/types';
import { toast } from '@/components/Toast';

const List: FC = () => {
    const navigate = useNavigate();
    const [nextCursor, setNextCursor] = useState<string | undefined>(undefined);
    const [previousCursor, setPreviousCursor] = useState<string | undefined>(undefined);
    const [filters, setFilters] = useState<FilterValues>({});
    const emailActions = useEmailActions();
    const [showModal, setShowModal] = useState(false);
    const { mutate: emptyTrash, isPending } = useEmptyTrash();
    const { data: trashData, isLoading, refetch, isFetching } = useGetTrashMessages({
        next: nextCursor,
        previous: previousCursor,
        limit: 10,
        ...filters
    });

    const [selectedMessages, setSelectedMessages] = useState<TrashMessage[]>([]);

    const columns: ColumnType<TrashMessage>[] = [
        {
            key: 'subject',
            title: 'عنوان پیام',
            render: (item) => (
                <span className="truncate">{item.subject || 'بدون موضوع'}</span>
            )
        },
        {
            key: 'from',
            title: 'فرستنده',
            render: (item) => (
                <div className="flex items-center">
                    {!item.seen && <div className="w-1.5 h-1.5 md:w-2 md:h-2 rounded-full bg-blue-500 ml-2" />}
                    <span className="truncate">{item.from.name || item.from.address}</span>
                </div>
            )
        },
        {
            key: 'date',
            title: 'تاریخ',
            align: 'center',
            render: (item) => (
                <span>{formatDate(item.date)}</span>
            )
        },
    ];

    const tableActions = (
        <div className='flex items-center gap-2 md:gap-4'>
            <Refresh2
                size={18}
                color='black'
                className={`cursor-pointer min-w-[18px] ${isFetching ? 'animate-spin-reverse' : ''}`}
                onClick={() => refetch()}
            />
            <Button
                label='خالی کردن سطل زباله'
                className='h-8'
                onClick={() => setShowModal(true)}
                loading={isPending}
            />
        </div>
    );

    const selectedActions = (
        <>
            <RecoveryConvert size={18} color='black' onClick={() => handleRestoreSelected()} className="cursor-pointer" />
            <Trash size={18} color='red' onClick={() => handleDeleteSelected()} className="cursor-pointer" />
        </>
    );

    const handleFilterChange = (newFilters: FilterValues) => {
        setFilters(newFilters);
        setNextCursor(undefined);
        setPreviousCursor(undefined);
    };

    const handleSelectionChange = (selectedRows: TrashMessage[]) => {
        setSelectedMessages(selectedRows);
    };

    const handleDeleteSelected = () => {
        const messageIds = selectedMessages.map(message => message.id);
        emailActions.bulkDelete(messageIds, selectedMessages[0].mailbox);
        setSelectedMessages([]);
    };

    const handleRestoreSelected = () => {
        const messageIds = selectedMessages.map(message => message.id);
        emailActions.bulkRestore(messageIds, selectedMessages[0].mailbox);
        setSelectedMessages([]);
    };

    const handleTrash = () => {
        emptyTrash(undefined, {
            onSuccess: () => {
                refetch();
                setShowModal(false);
            },
            onError: (error: ErrorType) => {
                toast(error.response?.data?.error.message[0], 'error')
            }
        });
    };

    const getRowActions = (message: TrashMessage): RowActionItem[] => [
        {
            label: 'بازگردانی',
            icon: <RecoveryConvert size={16} color="black" />,
            onClick: () => emailActions.restore({ messageId: message.id, mailbox: message.mailbox }),
        },
        {
            label: 'حذف دائم',
            icon: <Trash size={16} color="red" />,
            onClick: () => emailActions.deletePermanently({ messageId: message.id, mailbox: message.mailbox }),
        },
    ];

    const handleNext = (cursor?: string) => {
        setNextCursor(cursor);
        setPreviousCursor(undefined);
    };

    const handlePrevious = (cursor?: string) => {
        setPreviousCursor(cursor);
        setNextCursor(undefined);
    };

    const messages = trashData?.data?.trashMails || [];
    const pager = trashData?.data?.pager;

    return (
        <div className='mt-2 md:mt-4 px-2 md:px-0'>
            <h1 className="text-lg mb-4 md:mb-0">سطل زباله</h1>

            <Filters
                fields={[
                    { type: 'date', name: 'datestart', placeholder: 'از تاریخ' },
                    { type: 'date', name: 'dateend', placeholder: 'تا تاریخ' },
                    { type: 'input', name: 'search', placeholder: 'جستجو' }
                ]}
                onChange={handleFilterChange}
                searchField="search"
            />

            <Table<TrashMessage>
                columns={columns}
                data={messages}
                isLoading={isLoading || emailActions.isLoading}
                showHeader={false}
                actions={tableActions}
                selectedActions={selectedActions}
                onSelectionChange={handleSelectionChange}
                selectedRows={selectedMessages}
                onRowClick={(id, item) => navigate(`/mail/${id}/${item.mailbox}`)}
                noDataMessage={
                    <div className="flex flex-col items-center">
                        <InfoCircle size={32} className="text-gray-300 mb-2" />
                        <div className="text-sm">هیچ پیامی یافت نشد.</div>
                    </div>
                }
                selectable={true}
                rowActions={getRowActions}
                pagination={pager ? {
                    hasNext: typeof pager.nextCursor === 'string',
                    nextCursor: typeof pager.nextCursor === 'string' ? pager.nextCursor : undefined,
                    previousCursor: typeof pager.previousCursor === 'string' ? pager.previousCursor : undefined,
                    onNext: handleNext,
                    onPrevious: handlePrevious
                } : undefined}
            />

            <ModalConfrim
                isOpen={showModal}
                close={() => setShowModal(false)}
                onConfrim={handleTrash}
                isLoading={isPending}
            />
        </div>
    )
}

export default List
