"use client"

import { use, useState } from "react"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import { Badge } from "@/shared/components/ui/badge"
import { Tabs, TabsList, TabsTrigger } from "@/shared/components/ui/tabs"
import { JOB_CARD_ROUTES } from "@garage/api"
import type { JobCardsClient } from "@garage/api"
import { useRouter } from "next/navigation"
import { WrenchIcon } from "lucide-react"
import { formatEnum } from "@/shared/utils/formatters"

const ROLE_PARAM = {
    technician: "primary_technician_id",
    sales: "sales_person_id",
    writer: "service_writer_id",
} as const

type RoleKey = keyof typeof ROLE_PARAM

function formatDate(value: unknown) {
    if (!value || typeof value !== "string") return "—"
    const d = new Date(value)
    return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
}

function statusVariant(status: string | undefined): "default" | "secondary" | "outline" | "destructive" {
    if (!status) return "secondary"
    if (status === "completed" || status === "delivered") return "default"
    if (status === "cancelled") return "destructive"
    return "outline"
}

export default function EmployeeWorkHistoryPage({ params }: { params: Promise<{ id: string }> }) {
    const { id: employeeId } = use(params)
    const router = useRouter()
    const [role, setRole] = useState<RoleKey>("technician")
    const paramKey = ROLE_PARAM[role]

    return (
        <div className="space-y-3">
            <div className="px-4 pt-4">
                <Tabs value={role} onValueChange={(v) => setRole(v as RoleKey)}>
                    <TabsList variant="line">
                        <TabsTrigger value="technician">As Technician</TabsTrigger>
                        <TabsTrigger value="sales">As Sales Person</TabsTrigger>
                        <TabsTrigger value="writer">As Service Writer</TabsTrigger>
                    </TabsList>
                </Tabs>
            </div>

            <ResourcePage<JobCardsClient>
                key={role}
                pageTitle="Work History"
                routeKey={JOB_CARD_ROUTES.INDEX}
                searchable
                searchPlaceholder="Search by job number, plate, customer..."
                getClient={(api) => api.jobCards}
                extraParams={{ [paramKey]: employeeId }}
                header={null}
                onRowClick={(row) => router.push(`/sales/job-cards/${(row as any).id}`)}
                columns={() => [
                    {
                        accessorKey: "order_number",
                        header: ({ column }) => <ColumnHeader column={column} title="Job #" />,
                        cell: ({ row }) => (
                            <div className="flex items-center gap-2">
                                <WrenchIcon className="size-4 text-muted-foreground" />
                                <span className="font-mono text-xs">{(row.original as any).order_number ?? "—"}</span>
                            </div>
                        ),
                    },
                    {
                        accessorKey: "customer",
                        header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
                        cell: ({ row }) => {
                            const c = (row.original as any).customer
                            if (!c) return "—"
                            return `${c.first_name ?? ""} ${c.last_name ?? ""}`.trim() || c.email || "—"
                        },
                    },
                    {
                        accessorKey: "vehicle",
                        header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
                        cell: ({ row }) => {
                            const v = (row.original as any).vehicle
                            if (!v) return "—"
                            const display = `${v.make ?? ""} ${v.model ?? ""}`.trim()
                            return display || v.license_plate || "—"
                        },
                    },
                    {
                        accessorKey: "status",
                        header: ({ column }) => <ColumnHeader column={column} title="Status" />,
                        cell: ({ row }) => {
                            const s = (row.original as any).status
                            return s ? <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge> : "—"
                        },
                    },
                    {
                        accessorKey: "created_at",
                        header: ({ column }) => <ColumnHeader column={column} title="Opened" />,
                        cell: ({ row }) => formatDate((row.original as any).created_at),
                    },
                ]}
            />
        </div>
    )
}
