"use client"

import { ResourcePage } from '@/shared/data-view/resource-page'
import { ColumnHeader } from '@/shared/data-view/table-view'
import FormDialog from '@/shared/components/form-dialog'
import { JobCardForm } from '@/modules/job-cards/job-card-form'
import { JOB_CARD_ROUTES, JobCardStatus } from '@garage/api'
import type { JobCardsClient } from '@garage/api'
import { ClipboardListIcon, Printer } from 'lucide-react'
import { useDocumentPrint } from '@/shared/hooks/use-document-print'
import { Badge } from '@/shared/components/ui/badge'
import { useRouter } from 'next/navigation'
import { formatDate, formatEnum, formatNumber } from '@/shared/utils/formatters'
import { useFilterParams } from '@/shared/hooks/use-filter-params'
import { FilterDrawer, FilterTrigger } from '@/shared/components/filter-drawer'
import { jobCardFilterConfig, JobCardFilterFields } from '@/modules/job-cards/job-card-filters'

type JobCardItem = {
    id: number
    title?: string
    status?: string
    check_in_date?: string
    km_in?: number
    created_at?: string
}

const statusColorMap: Record<string, string> = {
    draft: "secondary",
    check_in: "default",
    in_progress: "default",
    completed: "default",
    invoiced: "outline",
    cancelled: "destructive",
}

export default function JobCardsPage() {
    const router = useRouter()
    const filter = useFilterParams(jobCardFilterConfig)
    const { print, isPrinting } = useDocumentPrint()

    return (
        <>
            <ResourcePage<JobCardsClient>
                routeKey={JOB_CARD_ROUTES.INDEX}
                getClient={(api) => api.jobCards}
                searchable
                searchPlaceholder="Search job cards..."
                statusFilter={{ statuses: JobCardStatus }}
                extraParams={filter.appliedParams}
                onRowClick={(row) => router.push(`/sales/job-cards/${row.id}`)}
                headerProps={({ selectedItem, invalidateQuery }) => ({
                    title: "Job Cards",
                    actions: (
                        <div className="flex items-center gap-2">
                            <FilterTrigger onClick={filter.open} activeFilterCount={filter.activeFilterCount} />
                            <FormDialog classNames={{ dialogContent: 'xl:min-w-6xl' }} title="Job Card" >
                                {(resourceId, {close}) => (
                                    <JobCardForm
                                        resourceId={resourceId}
                                        initialData={selectedItem}
                                        onSuccess={()=>{ invalidateQuery(); close();}}
                                    />
                                )}
                            </FormDialog>
                        </div>
                    ),
                })}
                columns={({ actionsColumn }) => [
                    {
                        accessorKey: "title",
                        header: ({ column }) => <ColumnHeader column={column} title="Title" />,
                        cell: ({ row }) => {
                            const item = row.original as unknown as JobCardItem
                            return (
                                <div className="flex items-center gap-2">
                                    <ClipboardListIcon className="text-muted-foreground h-4 w-4" />
                                    <span>{item.title}</span>
                                </div>
                            )
                        },
                    },
                    {
                        accessorKey: "order_number",
                        header: ({ column }) => <ColumnHeader column={column} title="Order Number" />,
                    },
                    {
                        accessorKey: "check_in_date",
                        header: ({ column }) => <ColumnHeader column={column} title="Check-in Date" />,
                        cell: ({ getValue }) => {
                            const val = getValue<string>()
                            return formatDate(val)
                        }
                    },
                    {
                        accessorKey: "vehicle_id",
                        header: ({ column }) => <ColumnHeader column={column} title="KM In" />,
                        cell: ({ row }) => {
                            const item = row.original as unknown as JobCardItem
                            return item.km_in ? formatNumber(item.km_in) : "—"
                        },
                    },
                    {
                        accessorKey: "created_at",
                        header: ({ column }) => <ColumnHeader column={column} title="Created" />,
                        cell: ({ row }) => {
                            const item = row.original as unknown as JobCardItem
                            return formatDate(item.created_at)
                        },
                    },
                    {
                        accessorKey: "status",
                        header: ({ column }) => <ColumnHeader column={column} title="Status" />,
                        cell: ({ row }) => {
                            const item = row.original as unknown as JobCardItem
                            return (
                                <Badge variant={statusColorMap[item.status ?? ""] as any ?? "outline"}>
                                    {formatEnum(item.status)}
                                </Badge>
                            )
                        },
                    },
                    actionsColumn({
                        extraItems: (row) => [
                            {
                                label: isPrinting ? "Printing..." : "Print",
                                icon: Printer,
                                onClick: (r) => print("job_card", String(r.id), "print"),
                            },
                        ],
                    }),
                ]}
            />

            <FilterDrawer
                form={filter.form}
                isOpen={filter.isOpen}
                onOpenChange={(open) => { if (!open) filter.close() }}
                onSubmit={filter.onSubmit}
                onReset={filter.reset}
                activeFilterCount={filter.activeFilterCount}
                title="Filter Job Cards"
            >
                <JobCardFilterFields />
            </FilterDrawer>
        </>
    )
}
