"use client"

import { useParams } from "next/navigation"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { type ColumnDef } from "@tanstack/react-table"
import { useState } from "react"
import { Plus, Pencil, Trash2, MoreHorizontal } from "lucide-react"
import { toast } from "sonner"

import { useAuthApi } from "@/shared/useApi"
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
import { confirm } from "@/shared/components/confirm-dialog"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent } from "@/shared/components/ui/card"
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from "@/shared/components/ui/dialog"
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { MileageForm } from "@/modules/vehicles/mileage-form"
import { formatDate, formatDateTime } from "@/shared/utils/formatters"

type MileageRecord = {
    id: number
    vehicle_id?: number
    miles?: number | null
    fuel_level?: number | null
    date?: string | null
    time?: string | null
    note?: string | null
    vehicle?: {
        id?: number
        make?: string | null
        model?: string | null
        year?: number | null
        license_plate?: string | null
    } | null
    created_at: string
    updated_at: string
}

export default function VehicleMileagePage() {
    const { id: vehicleId } = useParams<{ id: string }>()
    const api = useAuthApi()
    const queryClient = useQueryClient()
    const [dialogOpen, setDialogOpen] = useState(false)
    const [editItem, setEditItem] = useState<MileageRecord | null>(null)

    const queryKey = ["vehicle-mileage", vehicleId]

    const { data, isLoading } = useQuery({
        queryKey,
        queryFn: () => api.vehicleDocuments.listMileage({ vehicle_id: vehicleId }),
    })

    const deleteMutation = useMutation({
        mutationFn: (id: number) => {
            const promise = api.vehicleDocuments.destroyMileage(String(id))
            toast.promise(promise, {
                loading: "Deleting...",
                success: "Mileage record deleted successfully.",
                error: "Failed to delete mileage record.",
            })
            return promise
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey })
        },
    })

    const handleDelete = async (record: MileageRecord) => {
        const label = record.miles != null ? `${record.miles} mi` : `Record #${record.id}`
        const confirmed = await confirm({
            title: "Delete Mileage Record",
            description: `Are you sure you want to delete ${label}?`,
            confirmLabel: "Delete",
            variant: "destructive",
        })
        if (confirmed) {
            deleteMutation.mutate(record.id)
        }
    }

    const handleEdit = (record: MileageRecord) => {
        setEditItem(record)
        setDialogOpen(true)
    }

    const handleCreate = () => {
        setEditItem(null)
        setDialogOpen(true)
    }

    const columns: ColumnDef<MileageRecord>[] = [
        {
            accessorKey: "miles",
            header: ({ column }) => <ColumnHeader column={column} title="Miles" />,
            cell: ({ getValue }) => {
                const value = getValue<number | null | undefined>()
                return value == null ? "—" : value.toLocaleString()
            },
        },
        {
            accessorKey: "fuel_level",
            header: ({ column }) => <ColumnHeader column={column} title="Fuel Level" />,
            cell: ({ getValue }) => {
                const value = getValue<number | null | undefined>()
                return value == null ? "—" : `${value}%`
            },
        },
        {
            accessorKey: "date",
            header: ({ column }) => <ColumnHeader column={column} title="Date" />,
            cell: ({ getValue }) => formatDate(getValue<string | null | undefined>()),
        },
        {
            accessorKey: "time",
            header: ({ column }) => <ColumnHeader column={column} title="Time" />,
            cell: ({ getValue }) => {
                const value = getValue<string | null | undefined>()
                if (!value) return "—"
                if (value.includes("T")) {
                    const timePart = value.split("T")[1]
                    return timePart ? timePart.slice(0, 5) : "—"
                }
                return value.slice(0, 5)
            },
        },
        {
            accessorKey: "note",
            header: ({ column }) => <ColumnHeader column={column} title="Note" />,
            cell: ({ getValue }) => getValue<string | null | undefined>() || "—",
        },
        {
            id: "vehicle",
            header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
            cell: ({ row }) => {
                const vehicle = row.original.vehicle
                if (!vehicle) return "—"
                const details = [vehicle.make, vehicle.model, vehicle.year].filter(Boolean).join(" ")
                return details || vehicle.license_plate || "—"
            },
            enableSorting: false,
        },
        {
            accessorKey: "created_at",
            header: ({ column }) => <ColumnHeader column={column} title="Recorded At" />,
            cell: ({ getValue }) => formatDateTime(getValue<string | undefined>()),
        },
        {
            id: "actions",
            header: () => <span className="sr-only">Actions</span>,
            cell: ({ row }) => (
                <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon-sm">
                            <MoreHorizontal className="size-4" />
                            <span className="sr-only">Open menu</span>
                        </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                        <DropdownMenuItem onClick={() => handleEdit(row.original)}>
                            <Pencil className="size-3.5 text-muted-foreground" />
                            Edit
                        </DropdownMenuItem>
                        <DropdownMenuItem
                            variant="destructive"
                            onClick={() => handleDelete(row.original)}
                        >
                            <Trash2 className="size-3.5" />
                            Delete
                        </DropdownMenuItem>
                    </DropdownMenuContent>
                </DropdownMenu>
            ),
            enableSorting: false,
        },
    ]

    const records = (data as any)?.data ?? []
    const meta = (data as any)?.meta

    const pagination = {
        page: meta?.current_page ?? 1,
        pageSize: meta?.per_page ?? 15,
        pageCount: meta?.last_page ?? 1,
        total: meta?.total ?? 0,
    }

    return (
        <div className="flex flex-col gap-4">



            <Card>
                <CardContent>
                    <DataTable
                        slots={{
                            actions: <Button onClick={handleCreate}>
                                <Plus className="size-4" />
                                Add Mileage
                            </Button>
                        }}
                        columns={columns}
                        data={records}
                        pagination={pagination}
                        sorting={[]}
                        onChange={() => { }}
                        isLoading={isLoading}
                    />
                </CardContent>
            </Card>

            <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
                <DialogContent className="min-w-md">
                    <DialogHeader>
                        <DialogTitle>
                            {editItem ? "Edit Mileage" : "Add Mileage"}
                        </DialogTitle>
                    </DialogHeader>
                    <MileageForm
                        vehicleId={vehicleId}
                        resourceId={editItem ? String(editItem.id) : null}
                        initialData={editItem}
                        onSuccess={() => {
                            queryClient.invalidateQueries({ queryKey })
                            setDialogOpen(false)
                            setEditItem(null)
                        }}
                    />
                </DialogContent>
            </Dialog>
        </div>
    )
}
