
"use client"
import { confirm } from '@/shared/components/confirm-dialog';
 import { useRouter } from 'next/dist/client/components/navigation';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/shared/components/ui/dropdown-menu'
import { Button } from '@/shared/components/ui/button'
import { toast } from 'sonner'
import { CalendarPlus, Ellipsis, FileText, Pencil, Printer, Trash2 } from 'lucide-react';
import { useDocumentPrint } from '@/shared/hooks/use-document-print';
import { useJobCard } from './job-card-context';
import { useState } from 'react';
import { useAuthApi } from '@/shared/useApi';

// TODO: setting a sales person not working
// TODO: unable to set a Primary technician for the job card. Need to investigate and fix it.


export default function JobCardDropdown({ id }: { id: string }) {
    const  api  = useAuthApi()
    const router = useRouter();
    const { print, isPrinting } = useDocumentPrint()
    const jobCard = useJobCard()
    const [isConverting, setIsConverting] = useState(false)

    const handleEdit = () => {
        router.push(`/sales/job-cards/${id}/edit`)
    }

    const handlePrint = () => {
        print("job_card", id, "print")
    }

    const handleCreateAppointment = () => {
        router.push(`/sales/job-cards/${id}/appointments?create=1`)
    }

    const handleConvertToInvoice = async () => {
        const confirmed = await confirm({
            title: "Convert to Invoice",
            description: "This will create a new invoice from this job card. Do you want to continue?",
            confirmLabel: "Convert",
        })
        if (!confirmed) return

        setIsConverting(true)
        try {
            const res = await api.jobCards.convertToInvoice(id, {}) as any
            const invoiceId = res?.data?.id
            toast.success("Job card converted to invoice successfully")
            if (invoiceId) {
                router.push(`/sales/invoice/${invoiceId}`)
            }
        } catch (err: any) {
            const conflictId = err?.response?.data?.data?.invoice_id ?? err?.data?.data?.invoice_id
            if (conflictId) {
                toast.info("An invoice already exists for this job card.")
                router.push(`/sales/invoice/${conflictId}`)
            } else {
                 toast.error(err?.message || "Failed to convert job card to invoice")
            }
        } finally {
            setIsConverting(false)
        }
    }

    const handleDelete = async () => {
        const confirmed = await confirm({
            title: "Delete Job Card",
            description: "Are you sure you want to delete this job card? This action cannot be undone.",
            confirmLabel: "Delete",
            variant: "destructive",
        })
        if (confirmed) {
            const promise = api.jobCards.destroy(id)
            toast.promise(promise, {
                loading: "Deleting job card...",
                success: "Job card deleted successfully",
                error: "Failed to delete job card",
            })
            await promise
            router.push("/sales/job-cards")
        }
    }
    return (
        <div className="flex items-center gap-2">
            {jobCard?.status !== "draft" && (
                <Button variant="outline" onClick={handleConvertToInvoice} disabled={isConverting}>
                    <FileText className="size-4" />
                    {isConverting ? "Converting..." : "Convert to Invoice"}
                </Button>
            )}

            <Button variant="outline" onClick={handleCreateAppointment}>
                <CalendarPlus className="size-4" />
                Create Appointment
            </Button>

            <DropdownMenu>
                <DropdownMenuTrigger asChild>
                    <Button variant="outline" size="icon" className="self-stretch h-auto aspect-square">
                        <Ellipsis className="size-4" />
                    </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                    <DropdownMenuItem onClick={handleEdit}>
                        <Pencil className="size-4" />
                        Edit
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={handlePrint} disabled={isPrinting}>
                        <Printer className="size-4" />
                        {isPrinting ? "Printing..." : "Print"}
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onClick={handleCreateAppointment}>
                        <CalendarPlus className="size-4" />
                        Create Appointment
                    </DropdownMenuItem>
                    {jobCard?.status !== "draft" && (
                        <DropdownMenuItem onClick={handleConvertToInvoice} disabled={isConverting}>
                            <FileText className="size-4" />
                            {isConverting ? "Converting..." : "Convert to Invoice"}
                        </DropdownMenuItem>
                    )}
                    <DropdownMenuSeparator />
                    <DropdownMenuItem variant="destructive" onClick={handleDelete}>
                        <Trash2 className="size-4" />
                        Delete
                    </DropdownMenuItem>
                </DropdownMenuContent>
            </DropdownMenu>
        </div>
    )
}