"use client"

import * as React from "react"
import { type Row } from "@tanstack/react-table"
import { Loader, Check, SendHorizonal } 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 { Vendor } from "@/db/schema/vendors"
import { requestPQVendors } from "../service"

interface ApprovalVendorDialogProps
  extends React.ComponentPropsWithoutRef<typeof Dialog> {
  vendors: Row<Vendor>["original"][]
  showTrigger?: boolean
  onSuccess?: () => void
}

export function RequestPQVendorsDialog({
  vendors,
  showTrigger = true,
  onSuccess,
  ...props
}: ApprovalVendorDialogProps) {
  const [isApprovePending, startApproveTransition] = React.useTransition()
  const isDesktop = useMediaQuery("(min-width: 640px)")

  function onApprove() {
    startApproveTransition(async () => {
      const { error } = await requestPQVendors({
        ids: vendors.map((vendor) => vendor.id),
      })

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

      props.onOpenChange?.(false)
      toast.success("PQ successfully sent to vendors")
      onSuccess?.()
    })
  }

  if (isDesktop) {
    return (
      <Dialog {...props}>
        {showTrigger ? (
          <DialogTrigger asChild>
            <Button variant="outline" size="sm" className="gap-2">
              <SendHorizonal className="size-4" aria-hidden="true" />
              Request ({vendors.length})
            </Button>
          </DialogTrigger>
        ) : null}
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Confirm Vendor PQ requst</DialogTitle>
            <DialogDescription>
              Are you sure you want to request{" "}
              <span className="font-medium">{vendors.length}</span>
              {vendors.length === 1 ? " vendor" : " vendors"}?
              After sent, vendors will be notified and can submit PQ information.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="gap-2 sm:space-x-0">
            <DialogClose asChild>
              <Button variant="outline">Cancel</Button>
            </DialogClose>
            <Button
              aria-label="Request selected vendors"
              variant="default"
              onClick={onApprove}
              disabled={isApprovePending}
            >
              {isApprovePending && (
                <Loader
                  className="mr-2 size-4 animate-spin"
                  aria-hidden="true"
                />
              )}
              Request
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    )
  }

  return (
    <Drawer {...props}>
      {showTrigger ? (
        <DrawerTrigger asChild>
          <Button variant="outline" size="sm" className="gap-2">
            <Check className="size-4" aria-hidden="true" />
            Request ({vendors.length})
          </Button>
        </DrawerTrigger>
      ) : null}
      <DrawerContent>
        <DrawerHeader>
          <DrawerTitle>Confirm Vendor Approval</DrawerTitle>
          <DrawerDescription>
            Are you sure you want to request{" "}
            <span className="font-medium">{vendors.length}</span>
            {vendors.length === 1 ? " vendor" : " vendors"}?
            After sent, vendors will be notified and can submit PQ information.
          </DrawerDescription>
        </DrawerHeader>
        <DrawerFooter className="gap-2 sm:space-x-0">
          <DrawerClose asChild>
            <Button variant="outline">Cancel</Button>
          </DrawerClose>
          <Button
            aria-label="Request selected vendors"
            variant="default"
            onClick={onApprove}
            disabled={isApprovePending}
          >
            {isApprovePending && (
              <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" />
            )}
            Request
          </Button>
        </DrawerFooter>
      </DrawerContent>
    </Drawer>
  )
}