import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { useDifferenceDoc, commit, commitAll } from "@/hook/useDifference";
import { useLogin } from "@/state/user";
import { Fragment } from "react/jsx-runtime";

export function DifferencePage() {
    const { data, isLoading, error } = useDifferenceDoc();
    const userInfo = useLogin();

    if (!userInfo) {
        return <div className="p-4">
            <h2 className="text-3xl">
                Not logged in
            </h2>
        </div>
    }

    if (error) {
        return <div>Error: {String(error)}</div>
    }

    return (
        <div className="p-4">
            <Card>
                <CardHeader className="relative">
                    <Button className="absolute right-2 top-8" variant="ghost"
                        onClick={() => {commitAll("comic")}}
                    >Commit All</Button>
                    <CardTitle className="text-2xl">Difference</CardTitle>
                    <CardDescription>Scanned Files List</CardDescription>
                </CardHeader>
                <CardContent>
                    <Separator decorative />
                    {isLoading && <div>Loading...</div>}
                    {data?.map((c) => {
                        const x = c.value;
                        return (
                            <Fragment key={c.type}>
                                {x.map((y) => (
                                    <div key={y.path} className="flex items-center mt-2">
                                        <p
                                        className="flex-1 text-sm text-wrap">{y.path}</p>
                                        <Button
                                            className="flex-none ml-2"
                                            variant="outline"
                                            onClick={() => {commit(y.path, y.type)}}>
                                            Commit
                                        </Button>
                                    </div>
                                ))}
                            </Fragment>
                        )
                    })}
                </CardContent>
            </Card>
        </div>
    )
}

export default DifferencePage;