import {
  Description,
  Dialog,
  DialogBackdrop,
  DialogPanel,
  DialogTitle,
} from '@headlessui/react'
import type { Dispatch, SetStateAction } from 'react'
import { Link, useFetcher } from 'react-router'

import type { TAdResponse } from '~/apis/common/get-ads'
import { Button } from '~/components/ui/button'

type TProperties = {
  selectedAds?: TAdResponse
  setSelectedAds: Dispatch<SetStateAction<TAdResponse | undefined>>
}

export const DialogDelete = (properties: TProperties) => {
  const { selectedAds, setSelectedAds } = properties || {}
  const fetcher = useFetcher()

  return (
    <Dialog
      open={!!selectedAds}
      onClose={() => {
        if (fetcher.state === 'idle') {
          setSelectedAds(undefined)
        }
      }}
      className="relative z-50"
      transition
    >
      <DialogBackdrop
        className="fixed inset-0 bg-black/50 duration-300 ease-out data-[closed]:opacity-0"
        transition
      />
      <div className="fixed inset-0 flex w-screen justify-center overflow-y-auto p-0 max-sm:bg-white sm:items-center sm:p-4">
        <DialogPanel
          transition
          className="max-w-lg space-y-6 rounded-lg bg-white p-8 duration-300 ease-out data-[closed]:scale-95 data-[closed]:opacity-0 sm:shadow-lg"
        >
          <DialogTitle className="relative flex justify-start text-xl font-bold">
            Anda akan menghapus banner berikut?
          </DialogTitle>
          <Description className="space-y-1 text-center text-[#565658]">
            <img
              src={selectedAds?.image_url}
              alt={selectedAds?.image_url}
              className="aspect-[150/1] h-[50px] rounded object-contain"
            />
            <Button
              as={Link}
              to={selectedAds?.url || ''}
              variant="link"
              size="fit"
            >
              {selectedAds?.url}
            </Button>
          </Description>
          <div className="flex justify-end">
            <fetcher.Form
              method="POST"
              action={`/actions/admin/advertisements/delete/${selectedAds?.id}`}
              className="grid"
            >
              <Button
                type="submit"
                variant="newsDanger"
                className="text-md h-[42px] rounded-md"
                disabled={fetcher.state !== 'idle'}
                isLoading={fetcher.state !== 'idle'}
              >
                Hapus
              </Button>
            </fetcher.Form>
          </div>
        </DialogPanel>
      </div>
    </Dialog>
  )
}
