"use client"

import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Power } from "lucide-react"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { Badge } from "@/shared/components/ui/badge"
import { VendorForm } from "@/modules/vendors/vendor-form"
import { useAuthApi } from "@/shared/useApi"
import { VENDOR_ROUTES } from "@garage/api"
import type { VendorsClient } from "@garage/api"

export default function VendorsPage() {
    const router = useRouter()
    const api = useAuthApi()
    return (
        <ResourcePage<VendorsClient>
            pageTitle="Vendors"
            routeKey={VENDOR_ROUTES.INDEX}
            searchable
            searchPlaceholder="Search vendors..."
            getClient={(api) => api.vendors}
            onRowClick={(row) => router.push(`/purchase/vendor/${(row as any).id}`)}
            headerProps={({ selectedItem, invalidateQuery }) => ({
                actions: (
                    <FormDialog title="Vendor">
                        {(resourceId) => (
                            <VendorForm
                                resourceId={resourceId}
                                initialData={selectedItem}
                                onSuccess={invalidateQuery}
                            />
                        )}
                    </FormDialog>
                ),
            })}
            columns={({ actionsColumn }) => [
                {
                    accessorKey: "first_name",
                    header: ({ column }) => <ColumnHeader column={column} title="Name" />,
                    cell: ({ row }) => {
                        const r = row.original as any
                        const name = [r.first_name, r.last_name].filter(Boolean).join(" ")
                        return name || "—"
                    },
                },
                {
                    accessorKey: "company_name",
                    header: ({ column }) => <ColumnHeader column={column} title="Company" />,
                    cell: ({ row }) => (row.original as any).company_name || "—",
                },
                {
                    accessorKey: "email",
                    header: ({ column }) => <ColumnHeader column={column} title="Email" />,
                    cell: ({ row }) => (row.original as any).email || "—",
                },
                {
                    accessorKey: "is_active",
                    header: ({ column }) => <ColumnHeader column={column} title="Status" />,
                    cell: ({ row }) => {
                        const isActive = Boolean((row.original as any).is_active)
                        return (
                            <Badge variant={isActive ? "default" : "outline"}>
                                {isActive ? "Active" : "Inactive"}
                            </Badge>
                        )
                    },
                },
                {
                    accessorKey: "created_at",
                    header: ({ column }) => <ColumnHeader column={column} title="Created" />,
                    cell: ({ row }) => {
                        const val = (row.original as any).created_at
                        return val ? new Date(val).toLocaleDateString() : "—"
                    },
                },
                actionsColumn({
                    extraItems: (row) => {
                        const isActive = Boolean((row as any).is_active)
                        return [
                            {
                                label: isActive ? "Deactivate" : "Activate",
                                icon: Power,
                                onClick: async () => {
                                    try {
                                        await api.vendors.toggleStatus({ id: Number((row as any).id) } as any)
                                        toast.success(isActive ? "Vendor deactivated." : "Vendor activated.")
                                        router.refresh()
                                    } catch {
                                        toast.error("Failed to update vendor status.")
                                    }
                                },
                            },
                        ]
                    },
                }),
            ]}
        />
    )
}
