import { type FC, useState } from 'react'
import PageTitle from '../../components/PageTitle'
import { useGetJobs, useDeleteJob } from './hooks/useJobsData'
import { type Job } from './types/Types'
import PageLoading from '../../components/PageLoading'
import Error from '../../components/Error'
import PaginationUi from '../../components/PaginationUi'
import Td from '../../components/Td'
import TrashWithConfrim from '../../components/TrashWithConfrim'
import ModalCreateJob from './components/ModalCreateJob'

const JobsList: FC = () => {
    const [currentPage, setCurrentPage] = useState(1);
    const { data: jobsData, isLoading, error, refetch } = useGetJobs(currentPage)
    const deleteJobMutation = useDeleteJob();

    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 handleDeleteJob = async (jobId: string) => {
        await deleteJobMutation.mutateAsync(jobId);
        refetch()
    };

    const jobs = jobsData?.results?.jobs || [];
    const pager = jobsData?.results?.pager;

    const getJobTypeText = (type: string) => {
        switch (type) {
            case 'fullTime': return 'تمام وقت';
            case 'partTime': return 'پاره وقت';
            case 'contract': return 'قراردادی';
            default: return type;
        }
    };

    const truncateText = (text: string, maxLength: number = 100) => {
        return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
    };

    return (
        <div>
            <PageTitle />
            <ModalCreateJob />
            <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={'عملیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {jobs.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={6} className="text-center py-8 text-gray-500">
                                    هیچ شغلی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            jobs.map((job: Job) => (
                                <tr key={job._id} className='tr'>
                                    <Td text={job.title} />
                                    <Td text={truncateText(job.description)} />
                                    <Td text={job.location} />
                                    <Td text="">
                                        <span className="px-2 py-1 rounded-full text-xs bg-blue-100 text-blue-800">
                                            {getJobTypeText(job.type)}
                                        </span>
                                    </Td>
                                    <Td text={new Date(job.createdAt).toLocaleDateString('fa-IR')} />
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <TrashWithConfrim
                                                onDelete={() => handleDeleteJob(job._id)}
                                                isLoading={deleteJobMutation.isPending}
                                            />
                                        </div>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

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

export default JobsList