"use client"

import { useState } from "react"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { Plus, Trash2 } from "lucide-react"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/shared/components/ui/table"
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from "@/shared/components/ui/dialog"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { ResourceSelectorDialog } from "@/shared/components/resource-selector/resource-selector-dialog"
import { useAuthApi } from "@/shared/useApi"
import { PARTS_ROUTES, ESTIMATE_ROUTES } from "@garage/api"
import type { PartsClient } from "@garage/api"
import { partColumns } from "@/modules/parts/parts-columns"
import { EstimatePartConfigForm } from "./estimate-part-config-form"
import { toast } from "sonner"

type PartLine = {
    id: number
    part_id?: number
    title?: string
    quantity: number
    rate: number | string
    description?: string
    part:any
}

type SelectedPart = {
    id: number
    title?: string
    purchase_price?: string | number
}

export function EstimatePartsSection({ estimateId }: { estimateId: string }) {
    const api = useAuthApi()
    const queryClient = useQueryClient()
    const [pickerOpen, setPickerOpen] = useState(false)
    const [configPart, setConfigPart] = useState<SelectedPart | null>(null)

    const queryKey = [ESTIMATE_ROUTES.PARTS, estimateId]

    const { data, isLoading } = useQuery({
        queryKey,
        queryFn: async () => {
            const res = await api.estimates.listParts(estimateId)
            return ((res as any)?.data ?? []) as PartLine[]
        },
    })

    const items: PartLine[] = data ?? []

    const invalidate = () => queryClient.invalidateQueries({ queryKey })

    const updateMutation = useMutation({
        mutationFn: ({ lineId, payload }: { lineId: string; payload: { quantity?: number } }) =>
            api.estimates.updatePart(estimateId, lineId, payload),
        onSuccess: () => {
            toast.success("Part updated")
            invalidate()
        },
        onError: () => toast.error("Failed to update part"),
    })

    const removeMutation = useMutation({
        mutationFn: (lineId: string) => api.estimates.removePart(estimateId, lineId),
        onSuccess: invalidate,
        onError: () => toast.error("Failed to remove part"),
    })

    const handlePickerConfirm = (rows: any[]) => {
        const row = rows[0]
        if (!row) return
        setConfigPart({
            id: row.id,
            title: row.title ?? row.name,
            purchase_price: row.purchase_price,
        })
    }

    const getDisplayName = (item: PartLine) =>
        item.part.title ?? `Part #${item.part_id ?? item.id}`

    return (
        <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0">
                <CardTitle className="text-base">Parts</CardTitle>
                <Button size="sm" variant="outline" onClick={() => setPickerOpen(true)}>
                    <Plus className="size-4 mr-1" />
                    Add Part
                </Button>
            </CardHeader>
            <CardContent>
                {isLoading && <p className="text-sm text-muted-foreground">Loading...</p>}
                {!isLoading && items.length === 0 && (
                    <p className="text-sm text-muted-foreground">No parts added yet.</p>
                )}
                {items.length > 0 && (
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead className="w-100">Part</TableHead>
                                <TableHead className="w-24">Qty</TableHead>
                                <TableHead className="w-28">Rate</TableHead>
                                <TableHead>Description</TableHead>
                                <TableHead className="w-12" />
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {items.map((item) => (
                                <TableRow key={item.id}>
                                    <TableCell className="font-medium">{getDisplayName(item)}</TableCell>
                                    <TableCell>
                                        <Input
                                            type="number"
                                            min={1}
                                            defaultValue={item.quantity}
                                            onBlur={(e) =>
                                                updateMutation.mutate({
                                                    lineId: String(item.id),
                                                    payload: { quantity: Number(e.target.value) || 1 },
                                                })
                                            }
                                            className="h-8 w-20"
                                        />
                                    </TableCell>
                                    <TableCell className="text-sm text-muted-foreground tabular-nums">
                                        {Number(item.rate).toFixed(2)}
                                    </TableCell>
                                    <TableCell className="text-sm text-muted-foreground">
                                        {item.description || "—"}
                                    </TableCell>
                                    <TableCell>
                                        <Button
                                            type="button"
                                            variant="ghost"
                                            size="icon"
                                            onClick={() => removeMutation.mutate(String(item.id))}
                                            disabled={removeMutation.isPending}
                                        >
                                            <Trash2 className="h-4 w-4 text-destructive" />
                                        </Button>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                )}
            </CardContent>

            {/* Step 1: Pick a part (single-select) */}
            <ResourceSelectorDialog<PartsClient>
                title="Select Part"
                open={pickerOpen}
                onOpenChange={setPickerOpen}
                selectionMode="single"
                onConfirm={handlePickerConfirm}
                searchPlaceholder="Search parts by title, SKU, or part number..."
                crudProps={{
                    routeKey: PARTS_ROUTES.INDEX,
                    getClient: (api) => api.parts,
                    columns: [
                        partColumns.title,
                        partColumns.partNumber,
                        partColumns.manufacturer,
                        partColumns.purchasePrice,
                        partColumns.stock,
                    ],
                }}
            />

            {/* Step 2: Configure and add the selected part */}
            <Dialog open={!!configPart} onOpenChange={(v) => { if (!v) setConfigPart(null) }}>
                <DialogContent className="sm:max-w-lg">
                    <DialogHeader>
                        <DialogTitle className="text-xl font-bold">Configure Part</DialogTitle>
                    </DialogHeader>
                    <ScrollArea className="max-h-[70vh] px-1">
                        {configPart && (
                            <EstimatePartConfigForm
                                part={configPart}
                                estimateId={estimateId}
                                onSuccess={() => {
                                    setConfigPart(null)
                                    invalidate()
                                }}
                                onCancel={() => setConfigPart(null)}
                            />
                        )}
                    </ScrollArea>
                </DialogContent>
            </Dialog>
        </Card>
    )
}
