"use client"

import * as React from "react"
import { VendorMaterialsView } from "@/db/schema/vendors"
import { type Row } from "@tanstack/react-table"
import { Loader, Trash } from "lucide-react"
import { toast } from "sonner"

import { useMediaQuery } from "@/hooks/use-media-query"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  Drawer,
  DrawerClose,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerTitle,
  DrawerTrigger,
} from "@/components/ui/drawer"

import {  removeVendorMaterials } from "../service"

interface DeleteVendorItemsDialogProps
  extends React.ComponentPropsWithoutRef<typeof Dialog> {
  vendorId: number
  items: Row<VendorMaterialsView>["original"][]
  showTrigger?: boolean
  onSuccess?: () => void
}

export function DeleteVendorItemsDialog({
  vendorId,
  items,
  showTrigger = true,
  onSuccess,
  ...props
}: DeleteVendorItemsDialogProps) {
  const [isDeletePending, startDeleteTransition] = React.useTransition()
  const isDesktop = useMediaQuery("(min-width: 640px)")

  function onDelete() {
    startDeleteTransition(async () => {
      const { error } = await removeVendorMaterials({
        itemCodes: items.map((item) => item.itemCode).filter(Boolean) as string[],
        vendorId,
      })

      if (error) {
        toast.error(error)
        return
      }

      props.onOpenChange?.(false)
      toast.success(
        items.length === 1 
          ? "Item deleted successfully" 
          : `${items.length} items deleted successfully`
      )
      onSuccess?.()
    })
  }

  if (isDesktop) {
    return (
      <Dialog {...props}>
        {showTrigger ? (
          <DialogTrigger asChild>
            <Button variant="outline" size="sm">
              <Trash className="mr-2 size-4" aria-hidden="true" />
              Delete ({items.length})
            </Button>
          </DialogTrigger>
        ) : null}
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Are you absolutely sure?</DialogTitle>
            <DialogDescription>
              This action cannot be undone. This will permanently delete{" "}
              <span className="font-medium">{items.length}</span>
              {items.length === 1 ? " item" : " items"} from this vendor.
            </DialogDescription>
          </DialogHeader>
          
          {/* 삭제될 아이템 목록 미리보기 */}
          <div className="max-h-32 overflow-y-auto rounded-md border p-2">
            {items.map((item, index) => (
              <div key={item.itemCode || index} className="flex justify-between text-sm py-1">
                <span className="font-medium truncate">{item.itemName}</span>
                <span className="text-muted-foreground ml-2 flex-shrink-0">
                  {item.itemCode}
                </span>
              </div>
            ))}
          </div>
          
          <DialogFooter className="gap-2 sm:space-x-0">
            <DialogClose asChild>
              <Button variant="outline">Cancel</Button>
            </DialogClose>
            <Button
              aria-label="Delete selected items"
              variant="destructive"
              onClick={onDelete}
              disabled={isDeletePending}
            >
              {isDeletePending && (
                <Loader
                  className="mr-2 size-4 animate-spin"
                  aria-hidden="true"
                />
              )}
              Delete
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    )
  }

  return (
    <Drawer {...props}>
      {showTrigger ? (
        <DrawerTrigger asChild>
          <Button variant="outline" size="sm">
            <Trash className="mr-2 size-4" aria-hidden="true" />
            Delete ({items.length})
          </Button>
        </DrawerTrigger>
      ) : null}
      <DrawerContent>
        <DrawerHeader>
          <DrawerTitle>Are you absolutely sure?</DrawerTitle>
          <DrawerDescription>
            This action cannot be undone. This will permanently delete{" "}
            <span className="font-medium">{items.length}</span>
            {items.length === 1 ? " item" : " items"} from this vendor.
          </DrawerDescription>
        </DrawerHeader>
        
        {/* 삭제될 아이템 목록 미리보기 */}
        <div className="max-h-32 overflow-y-auto rounded-md border p-2 mx-4">
          {items.map((item, index) => (
            <div key={item.itemCode || index} className="flex justify-between text-sm py-1">
              <span className="font-medium truncate">{item.itemName}</span>
              <span className="text-muted-foreground ml-2 flex-shrink-0">
                {item.itemCode}
              </span>
            </div>
          ))}
        </div>
        
        <DrawerFooter className="gap-2 sm:space-x-0">
          <DrawerClose asChild>
            <Button variant="outline">Cancel</Button>
          </DrawerClose>
          <Button
            aria-label="Delete selected items"
            variant="destructive"
            onClick={onDelete}
            disabled={isDeletePending}
          >
            {isDeletePending && (
              <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" />
            )}
            Delete
          </Button>
        </DrawerFooter>
      </DrawerContent>
    </Drawer>
  )
}