import { useState } from 'react';
import { Head, Link, router } from '@inertiajs/react';
import AppLayout from '@/Layouts/AppLayout.jsx';

import { DateTime } from "luxon";

import { BreadcrumbItem, BreadcrumbPage, BreadcrumbSeparator } from "@/components/ui/breadcrumb";
import { Button } from '@/components/ui/button';
import Checkbox from "@/components/Checkbox";
import { Pagination, PaginationContent, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious } from "@/components/ui/pagination"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";

import { useToast } from "@/hooks/use-toast.js";

export default function Histories({ auth, histories }) {

    const { toast } = useToast();
    const [ids, setIds] = useState([]);

    const checkboxOnChangeHandler = (e) => {
        if (e.target.checked) {
            // Add to ids
            setIds([...ids, e.target.dataset.hid]);
        } else {
            setIds(ids.filter(id => id !== e.target.dataset.hid));
        }
    }

    const datetimeConversion = (iso8601) => {
        return DateTime.fromISO(iso8601).setZone(auth.user.settings.timezone).toFormat('dd-MM-yyyy HH:mm');
    }

    const deleteButtonOnClickHandler = () => {
        router.visit(route('comics.patchHistories'), {
            data: (ids.length > 0) ? { ids: ids } : { ids: 'all' },
            method: "PATCH",
            only: ['histories'],
            onSuccess: data => {
                toast({
                    title: "All set",
                    description: `The histories has been deleted.`,
                });
            }
        });
    }

    const removeDuplicatedButtonOnClickHandler = () => {
        router.visit(route('comics.destroyHistories'), {
            data: (ids.length > 0) ? { ids: ids } : { ids: 'all' },
            method: "DELETE",
            only: ['histories'],
            onSuccess: data => {
                toast({
                    title: "All set",
                    description: `The duplicated records has been deleted.`,
                });
            }
        });
    }

    return (
        <AppLayout auth={ auth } header={
            <>
                <BreadcrumbSeparator className="hidden lg:block" />
                <BreadcrumbItem>
                    <BreadcrumbPage>Histories</BreadcrumbPage>
                </BreadcrumbItem>
            </>
        }>
            <Head>
                <title>Histories</title>
            </Head>
            <div className="p-3 pt-1 w-[90%] mx-auto">
                <div className="flex justify-end gap-2">
                    <Button size="sm" variant="destructive" onClick={ () => deleteButtonOnClickHandler() }>
                        { ids.length > 0 ? `Delete selected (${ ids.length })` : "Delete All" }
                    </Button>

                    <Button size="sm" variant="destructive" onClick={ () => removeDuplicatedButtonOnClickHandler() }>
                        Remove duplicates
                    </Button>

                    <Button size="sm" asChild>
                        <Link href="?group=comic">
                            Group by Comics
                        </Link>
                    </Button>
                </div>
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Select</TableHead>
                            <TableHead>Chapter</TableHead>
                            <TableHead>Comic</TableHead>
                            <TableHead className="invisible lg:visible">Read at</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        { histories.data.map((h, i) => (
                            <TableRow key={ i }>
                                <TableCell>
                                    <label>
                                        <Checkbox data-hid={ h.hid } defaultChecked={ false }
                                                  name={ `checkbox-${ h.hid }` }
                                                  onChange={ (e) => checkboxOnChangeHandler(e) } />
                                    </label>
                                </TableCell>
                                <TableCell>
                                    <Link href={ route('comics.read', [h.comic.pathword, h.chapter_uuid]) }>
                                        { h.name }
                                    </Link>
                                </TableCell>
                                <TableCell>
                                    <Link href={ route('comics.chapters', [h.comic.pathword]) }>
                                        { h.comic.name }
                                    </Link>
                                </TableCell>
                                <TableCell className="invisible lg:visible">{ datetimeConversion(h.pivot.created_at) }</TableCell>
                            </TableRow>
                        )) }
                    </TableBody>
                </Table>
                <div>
                    <Pagination className="justify-end">
                        <PaginationContent>
                            { histories.current_page > 1 && (
                                <PaginationItem>
                                    <PaginationPrevious href={ histories.prev_page_url } only={['histories']} />
                                </PaginationItem>
                            ) }
                            <PaginationItem>
                                <PaginationLink href="#">{ histories.current_page }</PaginationLink>
                            </PaginationItem>
                            { histories.current_page < histories.last_page && (
                                <PaginationItem>
                                    <PaginationNext href={ histories.next_page_url } only={['histories']} />
                                </PaginationItem>
                            ) }
                        </PaginationContent>
                    </Pagination>
                </div>
            </div>
        </AppLayout>
    );
}
