"use client"

import { useMutation, useQueryClient } from "@tanstack/react-query"
import { toast } from "sonner"
import { StarIcon, StarOffIcon } from "lucide-react"

import { DepartmentForm } from "@/modules/settings/departments/department-form"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { Button } from "@/shared/components/ui/button"
import { useAuthApi } from "@/shared/useApi"
import { DEPARTMENT_ROUTES } from "@garage/api"
import type { DepartmentsClient } from "@garage/api"

function FavoriteCell({ row }: { row: any }) {
    const api = useAuthApi()
    const queryClient = useQueryClient()
    const isFavorite: boolean = row.is_favorite ?? false

    const { mutate, isPending } = useMutation({
        mutationFn: () => {
            const promise = isFavorite
                ? api.departments.removeFavorite({ id: row.id })
                : api.departments.setFavorite({ id: row.id })
            toast.promise(promise, {
                loading: isFavorite ? "Removing from favourites..." : "Setting as favourite...",
                success: isFavorite ? "Removed from favourites" : "Set as favourite",
                error: isFavorite ? "Failed to remove favourite" : "Failed to set favourite",
            })
            return promise
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: [DEPARTMENT_ROUTES.INDEX] })
        },
    })

    return (
        <Button
            variant="ghost"
            size="icon-sm"
            disabled={isPending}
            onClick={() => mutate()}
            title={isFavorite ? "Remove from favourites" : "Set as favourite"}
        >
            {isFavorite
                ? <StarIcon className="h-4 w-4 text-yellow-500 fill-yellow-400" />
                : <StarOffIcon className="h-4 w-4 text-muted-foreground" />}
        </Button>
    )
}

export default function DepartmentsPage() {
    return (
        <ResourcePage<DepartmentsClient>
            pageTitle="Departments"
            routeKey={DEPARTMENT_ROUTES.INDEX}
            getClient={(api) => api.departments}
            headerProps={({ selectedItem, invalidateQuery }) => ({
                actions: (
                    <FormDialog title="Department">
                        {(resourceId) => (
                            <DepartmentForm
                                resourceId={resourceId}
                                initialData={selectedItem}
                                onSuccess={invalidateQuery}
                            />
                        )}
                    </FormDialog>
                ),
            })}
            columns={({ actionsColumn }) => [
                {
                    accessorKey: "name",
                    header: ({ column }) => <ColumnHeader column={column} title="Name" />,
                },
                {
                    accessorKey: "assignment_type",
                    header: ({ column }) => <ColumnHeader column={column} title="Assignment Type" />,
                    cell: ({ row }) => (row.original as any).assignment_type ?? "none",
                },
                {
                    id: "favourite",
                    header: () => <span className="sr-only">Favourite</span>,
                    enableSorting: false,
                    cell: ({ row }) => <FavoriteCell row={row.original} />,
                },
                actionsColumn(),
            ]}
        />
    )
}