"use client"

import { useAuthApi } from "@/shared/useApi"
import { useRouter } from "next/navigation"
import { useState } from "react"
import { Button } from "@/shared/components/ui/button"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Pencil, Trash2, CheckCircle, Unlink } from "lucide-react"
import { toast } from "sonner"
import { useQueryClient } from "@tanstack/react-query"
import { APPOINTMENT_ROUTES } from "@garage/api"
import { useFormDialog } from "@/shared/components/form-dialog"
import { AppointmentForm } from "./appointment-form"

type AppointmentActionsProps = {
    appointmentId: string
    currentStatus?: string
    jobCardId?: number | null
}

export function AppointmentActions({ appointmentId, currentStatus, jobCardId }: AppointmentActionsProps) {
    const api = useAuthApi()
    const router = useRouter()
    const queryClient = useQueryClient()
    const [isLoading, setIsLoading] = useState(false)
    const editDialog = useFormDialog("appointment-details-edit")

    const handleDelete = async () => {
        setIsLoading(true)
        try {
            await api.appointments.destroy(appointmentId)
            toast.success("Appointment deleted.")
            router.push("/calendar/appointment/list")
        } catch {
            toast.error("Failed to delete appointment.")
        } finally {
            setIsLoading(false)
        }
    }

    const handleChangeStatus = async (status: string) => {
        setIsLoading(true)
        try {
            await api.appointments.changeStatus(appointmentId, { status } as any)
            toast.success(`Status updated to "${status}".`)
            queryClient.invalidateQueries({ queryKey: [APPOINTMENT_ROUTES.INDEX] })
            router.refresh()
        } catch {
            toast.error("Failed to update status.")
        } finally {
            setIsLoading(false)
        }
    }

    const handleUnlinkJobCard = async () => {
        if (!jobCardId) return
        setIsLoading(true)
        try {
            await api.appointments.unlinkJobCard(appointmentId, {} as any)
            toast.success("Job card unlinked.")
            queryClient.invalidateQueries({ queryKey: [APPOINTMENT_ROUTES.INDEX] })
            router.refresh()
        } catch {
            toast.error("Failed to unlink job card.")
        } finally {
            setIsLoading(false)
        }
    }

    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon" disabled={isLoading}>
                    <Ellipsis className="size-4" />
                </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => editDialog.open(appointmentId)}>
                    <Pencil className="size-4" />
                    Edit
                </DropdownMenuItem>
                {currentStatus !== "confirmed" && (
                    <DropdownMenuItem onClick={() => handleChangeStatus("confirmed")}>
                        <CheckCircle className="size-4" />
                        Confirm
                    </DropdownMenuItem>
                )}
                {currentStatus !== "completed" && (
                    <DropdownMenuItem onClick={() => handleChangeStatus("completed")}>
                        <CheckCircle className="size-4" />
                        Mark Completed
                    </DropdownMenuItem>
                )}
                {currentStatus !== "cancelled" && (
                    <DropdownMenuItem onClick={() => handleChangeStatus("cancelled")}>
                        <CheckCircle className="size-4" />
                        Cancel
                    </DropdownMenuItem>
                )}
                {jobCardId && (
                    <>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem onClick={handleUnlinkJobCard}>
                            <Unlink className="size-4" />
                            Unlink Job Card
                        </DropdownMenuItem>
                    </>
                )}
                <DropdownMenuSeparator />
                <DropdownMenuItem variant="destructive" onClick={handleDelete}>
                    <Trash2 className="size-4" />
                    Delete
                </DropdownMenuItem>
            </DropdownMenuContent>
        </DropdownMenu>
            <Dialog open={editDialog.isOpen} onOpenChange={(v) => { if (!v) editDialog.close() }}>
                <DialogContent className="min-w-xl lg:min-w-4xl">
                    <DialogHeader>
                        <DialogTitle className="text-2xl font-bold">Edit Appointment</DialogTitle>
                    </DialogHeader>
                    <ScrollArea className="max-h-[80vh] px-4">
                        <AppointmentForm
                            resourceId={editDialog.resourceId}
                            onSuccess={() => {
                                editDialog.close()
                                router.refresh()
                            }}
                        />
                    </ScrollArea>
                </DialogContent>
            </Dialog>
        </>    )
}
