"use client"

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

import { TaxForm } from "@/modules/settings/tax-rates/tax-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 { TAX_ROUTES } from "@garage/api"
import type { TaxesClient } from "@garage/api"

function TaxDefaultCell({ row }: { row: any }) {
    const api = useAuthApi()
    const queryClient = useQueryClient()
    const isDefault: boolean = row.is_default ?? false

    const { mutate, isPending } = useMutation({
        mutationFn: () => {
            const promise = isDefault
                ? api.taxes.removeDefault({ id: row.id })
                : api.taxes.setDefault({ id: row.id })
            toast.promise(promise, {
                loading: isDefault ? "Removing default..." : "Setting as default...",
                success: isDefault ? "Default removed" : "Set as default",
                error: isDefault ? "Failed to remove default" : "Failed to set as default",
            })
            return promise
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: [TAX_ROUTES.INDEX] })
        },
    })

    return (
        <Button
            variant="ghost"
            size="icon-sm"
            disabled={isPending}
            onClick={() => mutate()}
            title={isDefault ? "Remove default" : "Set as default"}
        >
            {isDefault
                ? <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 TaxesPage() {
    return (
        <ResourcePage<TaxesClient>
            pageTitle="Tax & Rates"
            routeKey={TAX_ROUTES.INDEX}
            searchable
            searchPlaceholder="Search tax rates..."
            getClient={(api) => api.taxes}
            headerProps={({ selectedItem, invalidateQuery }) => ({
                actions: (
                    <FormDialog title="Tax">
                        {(resourceId) => (
                            <TaxForm
                                resourceId={resourceId}
                                initialData={selectedItem}
                                onSuccess={invalidateQuery}
                            />
                        )}
                    </FormDialog>
                ),
            })}
            columns={({ actionsColumn }) => [
                {
                    accessorKey: "title",
                    header: ({ column }) => <ColumnHeader column={column} title="Title" />,
                },
                {
                    accessorKey: "rate",
                    header: ({ column }) => <ColumnHeader column={column} title="Rate (%)" />,
                    cell: ({ row }) => `${(row.original as any).rate ?? 0}%`,
                },
                {
                    accessorKey: "note",
                    header: ({ column }) => <ColumnHeader column={column} title="Note" />,
                    cell: ({ row }) => (
                        <span className="text-muted-foreground line-clamp-1">
                            {(row.original as any).note ?? "—"}
                        </span>
                    ),
                },
                {
                    accessorKey: "is_default",
                    header: ({ column }) => <ColumnHeader column={column} title="Default" />,
                    cell: ({ row }) => (row.original as any).is_default
                        ? <CheckIcon className="h-4 w-4 text-green-600" />
                        : <XIcon className="h-4 w-4 text-muted-foreground" />,
                },
                {
                    id: "set_default",
                    header: () => <span className="sr-only">Set Default</span>,
                    enableSorting: false,
                    cell: ({ row }) => <TaxDefaultCell row={row.original} />,
                },
                actionsColumn(),
            ]}
        />
    )
}
