import {
    Button,
    Container,
    Flex,
    Heading,
    SkeletonText,
    Table,
    TableContainer,
    Tbody,
    Td,
    Th,
    Thead,
    Tr,
    Icon,
    useDisclosure
} from "@chakra-ui/react"
import { useQuery, useQueryClient } from "@tanstack/react-query"
import { createFileRoute, useNavigate } from "@tanstack/react-router"
import { useEffect, useState } from "react"
import { z } from "zod"
import { FaPlus, FaPen, FaTrashAlt } from "react-icons/fa"
import { CoursesService } from "../../../client"
import Delete from "../../../components/Common/DeleteAlert"
//import Addcourse from "../../components/courses/Addcourse"
import { Link } from "@tanstack/react-router"
const CoursesSearchSchema = z.object({
    page: z.number().catch(1),
})

export const Route = createFileRoute("/_layout/Courses/Courses")({
    component: Courses,
    validateSearch: (search) => CoursesSearchSchema.parse(search),
})


const PER_PAGE = 100

function getcoursesQueryOptions({ page }: { page: number }) {
    return {
        queryFn: () =>
            CoursesService.readCourses({ skip: (page - 1) * PER_PAGE, limit: PER_PAGE }),
        queryKey: ["courses", { page }],
    }
}

function CoursesTable() {
    const [id, setId] = useState<string>('');
    const deleteModal = useDisclosure()
    const queryClient = useQueryClient()
    const { page } = Route.useSearch()
    const navigate = useNavigate({ from: Route.fullPath })
    const setPage = (page: number) =>
        navigate({ search: (prev) => ({ ...prev, page }) })

    const {
        data: courses,
        isPending,
        isPlaceholderData,
    } = useQuery({
        ...getcoursesQueryOptions({ page }),
        placeholderData: (prevData) => prevData,
    })

    const hasNextPage = !isPlaceholderData && courses?.data.length === PER_PAGE
    const hasPreviousPage = page > 1

    useEffect(() => {
        if (hasNextPage) {
            queryClient.prefetchQuery(getcoursesQueryOptions({ page: page + 1 }))
        }
    }, [page, queryClient, hasNextPage])

    return (
        <>
            <TableContainer>
                <Table size={{ base: "sm", md: "md" }}>
                    <Thead>
                        <Tr>
                            <Th>ID</Th>
                            <Th>Title</Th>
                            <Th>Short description</Th>
                            <Th>Actions</Th>
                        </Tr>
                    </Thead>
                    {isPending ? (
                        <Tbody>
                            <Tr>
                                {new Array(4).fill(null).map((_, index) => (
                                    <Td key={index}>
                                        <SkeletonText noOfLines={1} paddingBlock="16px" />
                                    </Td>
                                ))}
                            </Tr>
                        </Tbody>
                    ) : (
                        <Tbody>
                            {courses?.data.map((course) => (
                                <Tr key={course.id} opacity={isPlaceholderData ? 0.5 : 1}>
                                    <Td isTruncated maxWidth="20px">{course.id}</Td>
                                    <Td isTruncated maxWidth="50px">
                                        {course.title}
                                    </Td>
                                    <Td

                                        isTruncated
                                        maxWidth="250px"
                                    >
                                        {course.sort_description || "N/A"}
                                    </Td>
                                    <Td>
                                        <Button
                                            variant="primary"
                                            gap={1}
                                            fontSize={{ base: "sm", md: "inherit" }}
                                            as={Link}
                                            to={`/Courses/${course.id}/EditCourse`}
                                        >
                                            <Icon as={FaPen} />
                                        </Button>
                                        <Button
                                            marginLeft={2}
                                            variant="primary"
                                            gap={1}
                                            fontSize={{ base: "sm" }}
                                           onClick={() => {
                                                setId(course.id)
                                                deleteModal.onOpen()
                                            }}
                                        >
                                            <Icon as={FaTrashAlt} />
                                        </Button>
                                    </Td>

                                </Tr>
                            ))}
                        </Tbody>
                    )}
                </Table>
            </TableContainer>
            <Delete
                type={'Course'}
                id={id}
                isOpen={deleteModal.isOpen}
                onClose={deleteModal.onClose}
            />
            <Flex
                gap={4}
                //aligncourses="center"
                mt={4}
                direction="row"
                justifyContent="flex-end"
            >
                <Button onClick={() => setPage(page - 1)} isDisabled={!hasPreviousPage}>
                    Previous
                </Button>
                <span>Page {page}</span>
                <Button isDisabled={!hasNextPage} onClick={() => setPage(page + 1)}>
                    Next
                </Button>
            </Flex>
        </>
    )
}

function Courses() {
    return (
        <Container maxW="full">
            <Heading size="lg" textAlign={{ base: "center", md: "left" }} pt={12}>
                Courses Management
            </Heading>
            <Flex py={8} gap={4}>
                {/* TODO: Complete search functionality */}
                {/* <InputGroup w={{ base: '100%', md: 'auto' }}>
                    <InputLeftElement pointerEvents='none'>
                        <Icon as={FaSearch} color='ui.dim' />
                    </InputLeftElement>
                    <Input type='text' placeholder='Search' fontSize={{ base: 'sm', md: 'inherit' }} borderRadius='8px' />
                </InputGroup> */}
                <Button
                    variant="primary"
                    gap={1}
                    fontSize={{ base: "sm", md: "inherit" }}
                    as={Link} to="/Courses/AddCourse"
                >
                    <Icon as={FaPlus} /> Add Course
                </Button>
            </Flex>
            <CoursesTable />
        </Container>
    )
}
