import { type FC, useState } from 'react'
import PageTitle from '../../components/PageTitle'
import { useGetTickets } from './hooks/useTicketData'
import { type ITicket, type TicketStatus } from './types/Types'
import PageLoading from '../../components/PageLoading'
import Error from '../../components/Error'
import PaginationUi from '../../components/PaginationUi'
import Td from '../../components/Td'
import { Calendar, MessageQuestion, User as UserIcon, Category } from 'iconsax-react'
import Button from '@/components/Button'
import { useNavigate } from 'react-router-dom'
import { Pages } from '@/config/Pages'
import StatusWithText from '../../components/StatusWithText'

const TicketsList: FC = () => {

    const navigate = useNavigate();
    const [currentPage, setCurrentPage] = useState(1);
    const { data: ticketsData, isLoading, error } = useGetTickets(currentPage);

    if (isLoading) {
        return (
            <div className="flex justify-center items-center min-h-[400px]">
                <PageLoading />
            </div>
        );
    }

    if (error) {
        return (
            <div className="flex justify-center items-center min-h-[400px]">
                <Error errorText="خطا در بارگذاری تیکت‌ها" />
            </div>
        );
    }

    const tickets = ticketsData?.results?.tickets || [];
    const pager = ticketsData?.results?.pager;

    const formatDate = (dateString: string) => {
        if (!dateString) return '-';
        return new Date(dateString).toLocaleDateString('fa-IR');
    };

    const getStatusVariant = (status: TicketStatus) => {
        switch (status) {
            case 'closed': return 'error';
            case 'answered': return 'success';
            case 'pending': return 'warning';
            default: return 'warning';
        }
    };

    const getStatusText = (status: TicketStatus) => {
        switch (status) {
            case 'closed': return 'بسته شده';
            case 'answered': return 'پاسخ داده شده';
            case 'pending': return 'در انتظار';
            default: return status;
        }
    };

    return (
        <div>
            <PageTitle />
            <div className='relative overflow-x-auto rounded-3xl mt-5 w-full'>
                <table className='w-full text-sm'>
                    <thead className='thead'>
                        <tr>
                            <Td text={'شماره تیکت'} />
                            <Td text={'فروشنده'} />
                            <Td text={'موضوع'} />
                            <Td text={'دسته‌بندی'} />
                            <Td text={'وضعیت'} />
                            <Td text={'تاریخ بروزرسانی'} />
                            <Td text={'عملیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {tickets.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={7} className="text-center py-8 text-gray-500">
                                    هیچ تیکتی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            tickets.map((ticket: ITicket) => (
                                <tr key={ticket._id} className='tr'>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <MessageQuestion size={16} color="#8C90A3" />
                                            <span>{ticket.numericId}</span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <UserIcon size={16} color="#8C90A3" />
                                            <span>{ticket.seller?.fullName || '-'}</span>
                                        </div>
                                    </Td>
                                    <Td text={ticket.subject} />
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Category size={16} color="#8C90A3" />
                                            <span>{ticket.category?.title_fa || '-'}</span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <StatusWithText
                                            variant={getStatusVariant(ticket.status)}
                                            text={getStatusText(ticket.status)}
                                        />
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Calendar size={16} color="#8C90A3" />
                                            <span>{formatDate(ticket.updatedAt)}</span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Button
                                                label='مشاهده'
                                                onClick={() => navigate(`${Pages.ticket.detail}${ticket._id}`)}
                                                className='h-8 text-xs'
                                            />
                                        </div>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

            <PaginationUi
                pager={pager}
                onPageChange={(page) => {
                    setCurrentPage(page);
                }}
            />
        </div>
    )
}

export default TicketsList