import Filters, { FilterValues } from '../../components/Filters';
import { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Table from '../../components/Table';
import { ColumnType } from '../../components/types/TableTypes';
import { InfoCircle, More, Refresh2, Trash, Edit, Send } from 'iconsax-react';
import { RowActionItem } from '../../components/RowActionsDropdown';
import { useNavigate } from 'react-router-dom';
import { useGetDrafts } from './hooks/useDraftData';
import { DraftMessage } from './types/DraftTypes';
import { formatDate } from '@/config/func';
import { useEmailActions } from '@/hooks/useEmailActions';
import { useSharedStore } from '@/shared/store/sharedStore';

const List: FC = () => {
    const navigate = useNavigate();
    const { t } = useTranslation();
    const [nextCursor, setNextCursor] = useState<string | undefined>(undefined);
    const [previousCursor, setPreviousCursor] = useState<string | undefined>(undefined);
    const [filters, setFilters] = useState<FilterValues>({});
    const emailActions = useEmailActions();
    const { setDraftData, setOpenNewMessage, setEditingDraftId } = useSharedStore();

    const { data: draftData, isLoading, refetch, isFetching } = useGetDrafts({
        next: nextCursor,
        previous: previousCursor,
        limit: 10,
        ...filters
    });

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

    const columns: ColumnType<DraftMessage>[] = [
        {
            key: 'title',
            title: 'title',
            render: () => (
                <div className="text-[#0038FF]">
                    پیش نویس
                </div>
            )
        },
        {
            key: 'subject',
            title: 'عنوان پیام',
            render: (item) => (
                <div className="flex items-center">
                    <span className="truncate">{item.subject || 'بدون موضوع'}</span>
                </div>
            )
        },
        {
            key: 'to',
            title: 'گیرنده',
            render: (item) => (
                <span className="truncate">
                    {item.to && item.to.length > 0
                        ? (item.to[0].name || item.to[0].address)
                        : 'بدون گیرنده'
                    }
                </span>
            )
        },
        {
            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 ${isFetching ? 'animate-spin-reverse' : ''}`}
                onClick={() => refetch()}
            />
            <More size={18} color='black' className='rotate-90 cursor-pointer' />
        </div>
    );

    const selectedActions = (
        <>
            <Send
                size={18}
                color='black'
                onClick={() => handleSendSelected()}
                className="cursor-pointer"
            />
            <Edit
                size={18}
                color='black'
                onClick={() => handleEditSelected()}
                className="cursor-pointer"
            />
            <Trash
                size={18}
                color='black'
                onClick={() => handleDeleteSelected()}
                className="cursor-pointer"
            />
        </>
    );

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

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

    const handleDeleteSelected = () => {
        selectedMessages.forEach(message => {
            emailActions.deleteDraft({ messageId: message.id, mailbox: message.mailbox });
        });
        setSelectedMessages([]);
    };

    const handleSendSelected = () => {
        selectedMessages.forEach(message => {
            emailActions.sendDraft({ messageId: message.id });
        });
        setSelectedMessages([]);
    };

    const handleEditSelected = () => {
        if (selectedMessages.length === 1) {
            navigate(`/draft/edit/${selectedMessages[0].id}`);
        } else {
            console.log('ویرایش چندین پیش‌نویس انتخاب شده:', selectedMessages.map(m => m.id));
        }
    };

    const handleDeleteDraft = (messageId: number) => {
        emailActions.deleteDraft({ messageId: messageId, mailbox: '' });
    };

    const handleSendDraft = (messageId: number) => {
        emailActions.sendDraft({ messageId: messageId });
    };

    const handleEditDraft = (messageId: number) => {
        navigate(`/draft/edit/${messageId}`);
    };

    const handleRowClick = (messageId: number, item: DraftMessage) => {
        setDraftData(item);
        setEditingDraftId(messageId);
        setOpenNewMessage(true);
    };

    const getRowActions = (message: DraftMessage): RowActionItem[] => [
        {
            label: 'ارسال',
            icon: <Send size={16} color="black" />,
            onClick: () => handleSendDraft(message.id),
        },
        {
            label: 'ویرایش',
            icon: <Edit size={16} color="black" />,
            onClick: () => handleEditDraft(message.id),
        },
        {
            label: 'حذف',
            icon: <Trash size={16} color="red" />,
            onClick: () => handleDeleteDraft(message.id),
        },
    ];



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

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

    const messages = draftData?.data?.draftMails || [];
    const pager = draftData?.data?.pager;

    return (
        <div className='mt-2 md:mt-4 px-2 md:px-0'>
            <h1 className="text-lg mb-4 md:mb-0">{t('draft.title')}</h1>

            <Filters
                fields={[
                    { type: 'date', name: 'datestart', placeholder: t('draft.from_date') },
                    { type: 'date', name: 'dateend', placeholder: t('draft.to_date') },
                    { type: 'input', name: 'search', placeholder: t('draft.search') }
                ]}
                onChange={handleFilterChange}
                searchField="search"
            />

            <Table<DraftMessage>
                columns={columns}
                data={messages}
                isLoading={isLoading || emailActions.isLoading}
                showHeader={false}
                actions={tableActions}
                selectedActions={selectedActions}
                onSelectionChange={handleSelectionChange}
                selectedRows={selectedMessages}
                onRowClick={handleRowClick}
                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}
            />
        </div>
    )
}

export default List
