"use client"
import { z } from "zod"
import { Button } from "@/components/ui/button"
import { Drawer, DrawerClose, DrawerContent, DrawerFooter, DrawerHeader, DrawerTrigger } from "@/components/ui/drawer"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useSortable } from "@dnd-kit/sortable"
import { IconGripVertical } from "@tabler/icons-react"
import { useIsMobile } from "@/hooks/use-mobile"
import { Separator } from "@/components/ui/separator"
import { ColumnDef, flexRender, Row } from "@tanstack/react-table"
import { TableCell, TableRow } from "@/components/ui/table"
import { CSS } from "@dnd-kit/utilities"
import { schema, schemaType } from "./schema"
import { dateToLocaleString } from "@/lib/utils"
import { Pencil, Trash } from "lucide-react"

function TableCellViewer({ item }: { item: schemaType }) {
    const isMobile = useIsMobile();

    return (
        <Drawer direction={isMobile ? "bottom" : "right"}>
            <DrawerTrigger asChild>
                <Button variant="link" className="text-foreground w-fit px-0 text-left">
                    {item.email ?? "Unknown Email"}
                </Button>
            </DrawerTrigger>

            <DrawerContent>
                <DrawerHeader className="gap-1">
                    <h2 className="text-lg font-semibold">{item.email}</h2>
                    <p className="text-sm text-muted-foreground">
                        User details
                    </p>
                </DrawerHeader>

                <div className="flex flex-col gap-4 overflow-y-auto px-4 text-sm">

                    {/* BASIC INFO */}
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <Label>Email</Label>
                            <Input value={item.email ?? ""} readOnly />
                        </div>

                        <div>
                            <Label>Phone</Label>
                            <Input value={item.phone ?? ""} readOnly />
                        </div>

                        <div>
                            <Label>Tag</Label>
                            <Input value={item.tag ?? ""} readOnly />
                        </div>

                        <div>
                            <Label>Active</Label>
                            <Input value={item.active ? "Active" : "Inactive"} readOnly />
                        </div>
                    </div>

                    <Separator />

                    {/* DATES */}
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <Label>Created At</Label>
                            <Input
                                value={item.createdAt ? new Date(item.createdAt).toLocaleString() : ""}
                                readOnly
                            />
                        </div>

                        <div>
                            <Label>Updated At</Label>
                            <Input
                                value={item.updatedAt ? new Date(item.updatedAt).toLocaleString() : ""}
                                readOnly
                            />
                        </div>
                    </div>

                    <Separator />

                    {/* TOKENS */}
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button variant="outline" className="w-full">
                                Collection Tokens ({item.collectionTokens?.tokens?.length ?? 0})
                            </Button>
                        </DropdownMenuTrigger>

                        <DropdownMenuContent className="w-72">
                            <DropdownMenuLabel>Tokens</DropdownMenuLabel>
                            <DropdownMenuSeparator />
                            {(item.collectionTokens?.tokens ?? []).length === 0 && (<DropdownMenuItem disabled>No tokens found</DropdownMenuItem>)}
                            {(item.collectionTokens?.tokens ?? []).map((t, i) => (
                                <DropdownMenuItem key={i} className="flex flex-col gap-2">
                                    <div className="grid grid-cols-2 gap-2 w-full">
                                        <Input value={t.prefix} readOnly />
                                        <Input value={t.token} readOnly />
                                    </div>
                                </DropdownMenuItem>
                            ))}
                        </DropdownMenuContent>
                    </DropdownMenu>

                </div>

                <DrawerFooter>
                    <DrawerClose asChild>
                        <Button variant="outline">Close</Button>
                    </DrawerClose>
                </DrawerFooter>
            </DrawerContent>
        </Drawer>
    );
}

function DragHandle({ id }: { id: number }) {
    const { attributes, listeners } = useSortable({ id })
    return (
        <Button {...attributes} {...listeners} variant="ghost" size="icon" className="text-muted-foreground size-7 hover:bg-transparent">
            <IconGripVertical className="text-muted-foreground size-3" />
            <span className="sr-only">Drag to reorder</span>
        </Button>
    )
}

export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
    const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
    return (
        <TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
            className="relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80"
            style={{ transform: CSS.Transform.toString(transform), transition: transition }}
        >
            {row.getVisibleCells().map((cell) => (
                <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
            ))}
        </TableRow>
    )
}

function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef<schemaType>[] {
    return [
        {
            accessorKey: "uuid",
            header: "UUID",
            cell: ({ getValue }) => (<div className="font-mono text-xs bg-muted px-2 py-1 rounded break-all">{String(getValue())}</div>),
        },
        {
            accessorKey: "email",
            header: "Email",
        },
        {
            accessorKey: "phone",
            header: "Phone",
        },
        {
            accessorKey: "tag",
            header: "Tag",
        },
        {
            accessorKey: "active",
            header: "Active",
            cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
        },
        {
            accessorKey: "isConfirmed",
            header: "Confirmed",
            cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
        },
        {
            accessorKey: "createdAt",
            header: "Created",
            cell: ({ getValue }) => dateToLocaleString(getValue() as string),
        },
        {
            accessorKey: "updatedAt",
            header: "Updated",
            cell: ({ getValue }) => dateToLocaleString(getValue() as string),
        },
        {
            accessorKey: "expiryStarts",
            header: "Expiry Starts",
            cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
        },
        {
            accessorKey: "expiryEnds",
            header: "Expiry Ends",
            cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
        },
        {
            accessorKey: "crypUuId",
            header: "Encrypted UUID",
        },
        {
            accessorKey: "history",
            header: "History",
            cell: ({ getValue }) => (<div className="truncate max-w-[150px] text-xs text-muted-foreground">{String(getValue() ?? "")}</div>),
        },
        {
            accessorKey: "collectionTokens.tokens",
            header: "Tokens",
            cell: ({ row }) => {
                const tokens = row.original.collectionTokens?.tokens ?? [];
                const defaultToken = row.original.collectionTokens?.default;
                if (!tokens.length) return "-";
                return (
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button variant="outline" className="h-8 px-2 text-xs">
                                Tokens ({tokens.length})
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent className="w-72">
                            <DropdownMenuLabel>Collection Tokens</DropdownMenuLabel>
                            <DropdownMenuSeparator />
                            {defaultToken && (
                                <>
                                    <DropdownMenuItem>
                                        <div className="flex flex-col w-full">
                                            <span className="font-semibold">Default</span>
                                            <span className="font-mono text-xs text-muted-foreground break-all">
                                                {defaultToken}
                                            </span>
                                        </div>
                                    </DropdownMenuItem>
                                    <DropdownMenuSeparator />
                                </>
                            )}
                            {tokens.map((t, i) => (
                                <DropdownMenuItem key={i} className="flex flex-col items-start">
                                    <div className="w-full flex justify-between">
                                        <span className="font-medium">{t.prefix}</span>
                                        <span className="font-mono text-muted-foreground break-all">
                                            {t.token}
                                        </span>
                                    </div>
                                </DropdownMenuItem>
                            ))}
                        </DropdownMenuContent>
                    </DropdownMenu>
                );
            },
        },
        {
            id: "actions",
            header: "Actions",
            cell: ({ row }) => {
                return (
                    <div>
                        <Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/users/update?uuid=${row.original.uuid}`) }}>
                            <Pencil />
                        </Button>
                        <Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>
                            <Trash />
                        </Button>
                    </div>
                );
            },
        }
    ]
}

export { getColumns };