"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 { Tabs, TabsList, TabsTrigger } from '@/shared/components/ui/tabs'
import { ClipboardListIcon, SearchIcon } from 'lucide-react'
import { Badge } from '@/shared/components/ui/badge'
import { Input } from '@/shared/components/ui/input'
import { useRouter } from 'next/navigation'
import { useState, useEffect } from 'react'
import { formatDate, formatEnum, formatNumber } from '@/shared/utils/formatters'

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 [searchInput, setSearchInput] = useState("")
    const [search, setSearch] = useState("")
    const [statusFilter, setStatusFilter] = useState<string>("check_in")

    useEffect(() => {
        const timer = setTimeout(() => setSearch(searchInput), 400)
        return () => clearTimeout(timer)
    }, [searchInput])

    const extraParams: Record<string, unknown> = {}
    if (search) extraParams.search = search
    if (statusFilter !== "all") extraParams.status = statusFilter

    return (
        <ResourcePage<JobCardsClient>
             
            routeKey={JOB_CARD_ROUTES.INDEX}
            getClient={(api) => api.jobCards}
            extraParams={extraParams}
            onRowClick={(row) => router.push(`/sales/job-cards/${row.id}`)}
            headerProps={({ selectedItem, invalidateQuery }) => ({
                title: "Job Cards",
                actions: (
                    <FormDialog classNames={{ dialogContent: 'min-w-6xl' }} title="Job Card" >
                        {(resourceId, {close}) => (
                            <JobCardForm
                                resourceId={resourceId}
                                initialData={selectedItem}
                                onSuccess={()=>{ invalidateQuery(); close();}}
                            />
                        )}
                    </FormDialog>
                ),
            })}
            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(),
            ]}

            tableHeader={
                <div className="flex justify-between">
                    <Tabs value={statusFilter} onValueChange={setStatusFilter}>
                        <TabsList variant="line">
                            <TabsTrigger  value="all" >All</TabsTrigger>
                            {JobCardStatus.map((status) => (
                                <TabsTrigger  key={status} value={status}>
                                    {formatEnum(status)}
                                </TabsTrigger>
                            ))}
                        </TabsList>
                    </Tabs>
                    <div className="relative w-64">
                        <SearchIcon className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                        <Input
                            placeholder="Search job cards..."
                            value={searchInput}
                            onChange={(e) => setSearchInput(e.target.value)}
                            className="pl-8"
                        />
                    </div>
                </div>
            }
        />
    )
}
