
"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, Loader2, Pencil, Printer, Share2, 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';
import { ShareDocumentDialog } from '@/shared/components/share-document-dialog';
import { ShareDocumentButton } from '@/shared/components/share-document-button';

// 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 [shareOpen, setShareOpen] = 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 existingInvoice = (jobCard as any)?.invoices?.[0] as { id: number | string; invoice_number?: string | null } | undefined

    const handleOpenExistingInvoice = () => {
        if (existingInvoice?.id != null) {
            router.push(`/sales/invoice/${existingInvoice.id}`)
        }
    }

    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)
        const promise = api.jobCards.convertToInvoice(id, {}) as Promise<any>
        toast.promise(promise, {
            loading: "Converting job card to invoice...",
            success: "Job card converted to invoice successfully",
            error: (err: any) => {
                const conflictId = err?.response?.data?.data?.invoice_id ?? err?.data?.data?.invoice_id
                return conflictId
                    ? "An invoice already exists for this job card."
                    : (err?.message || "Failed to convert job card to invoice")
            },
        })
        try {
            const res = await promise
            const invoiceId = res?.data?.id
            if (invoiceId) {
                router.push(`/sales/invoice/${invoiceId}`)
                return
            }
        } catch (err: any) {
            const conflictId = err?.response?.data?.data?.invoice_id ?? err?.data?.data?.invoice_id
            if (conflictId) {
                router.push(`/sales/invoice/${conflictId}`)
                return
            }
        }
        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" && (
                existingInvoice ? (
                    <Button variant="outline" onClick={handleOpenExistingInvoice}>
                        <FileText className="size-4" />
                        {existingInvoice.invoice_number ? `Invoice #${existingInvoice.invoice_number}` : "View Invoice"}
                    </Button>
                ) : (
                    <Button variant="outline" onClick={handleConvertToInvoice} disabled={isConverting}>
                        {isConverting ? <Loader2 className="size-4 animate-spin" /> : <FileText className="size-4" />}
                        {isConverting ? "Converting..." : "Convert to Invoice"}
                    </Button>
                )
            )}

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

            <ShareDocumentButton type="job_card" id={id} />

            <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>
                    <DropdownMenuItem onClick={() => setShareOpen(true)}>
                        <Share2 className="size-4" />
                        Share
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onClick={handleCreateAppointment}>
                        <CalendarPlus className="size-4" />
                        Create Appointment
                    </DropdownMenuItem>
                    {jobCard?.status !== "draft" && (
                        existingInvoice ? (
                            <DropdownMenuItem onClick={handleOpenExistingInvoice}>
                                <FileText className="size-4" />
                                {existingInvoice.invoice_number ? `Invoice #${existingInvoice.invoice_number}` : "View Invoice"}
                            </DropdownMenuItem>
                        ) : (
                            <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>

            <ShareDocumentDialog type="job_card" id={id} open={shareOpen} onOpenChange={setShareOpen} />
        </div>
    )
}