'use client'

import * as React from 'react'
import type { AdminMedia } from '@admin/types'
import { MediaGalleryDialog } from '@admin/components/shared/media/media-gallery-dialog'
import { MediaPreview } from '@admin/components/shared/media/media-preview'
import { Button } from '@admin/components/ui/button'
import { Card, CardContent, CardFooter } from '@admin/components/ui/card'
import { useCopyToClipboard } from '@admin/hooks/use-copy-to-clipboard'
import { useMediaById } from '@admin/hooks/use-media'
import { createAdminMediaFromUrl } from '@admin/utils/media/create-admin-media-from-url'
import { cn } from '@admin/utils/shared/cn'
import { Check, Copy, Link2 } from 'lucide-react'
import Link from 'next/link'
import { MediaFieldEmptyState } from './media-field-empty-state'

type MediaFieldValueMode = 'id' | 'url'
type MediaFieldFooterMode = 'url' | 'filename' | 'none'

interface MediaFieldProps {
  value?: string
  onChange: (value: string) => void
  onBlur?: () => void
  onRemove?: () => void
  media?: AdminMedia | null
  accept?: string
  disabled?: boolean
  className?: string
  isRemovable?: boolean
  valueMode?: MediaFieldValueMode
  footerMode?: MediaFieldFooterMode
}

export function MediaField({
  value,
  onChange,
  onBlur,
  onRemove,
  media: mediaOverride,
  accept,
  disabled,
  className,
  isRemovable = false,
  valueMode = 'id',
  footerMode = 'url'
}: MediaFieldProps) {
  const [open, setOpen] = React.useState(false)
  const { data: media } = useMediaById(
    valueMode === 'id' && mediaOverride === undefined ? value : undefined
  )
  const [copyMediaUrl, hasCopiedMediaUrl] = useCopyToClipboard()
  const selectedMedia =
    mediaOverride ??
    media ??
    (valueMode === 'url' && value ? createAdminMediaFromUrl(value, accept) : null)

  function handleSelect(selected: AdminMedia | AdminMedia[]) {
    const item = Array.isArray(selected) ? selected[0] : selected
    if (item) {
      onChange(valueMode === 'url' ? item.url : item.id)
    }
  }

  function handleRemove(e: React.MouseEvent) {
    e.preventDefault()
    e.stopPropagation()
    if (isRemovable && onRemove) {
      onRemove()
      return
    }
    onChange('')
    onBlur?.()
  }

  function handleChangeImage(e: React.MouseEvent) {
    e.preventDefault()
    e.stopPropagation()
    setOpen(true)
  }

  if (selectedMedia?.url) {
    return (
      <div className={cn('group relative', className)}>
        <Card className="p-0">
          <CardContent className="relative p-0!">
            <div
              data-media-field-preview
              className="relative aspect-video overflow-hidden rounded-sm bg-background"
            >
              <MediaPreview media={selectedMedia} showMetadata={Boolean(media)} />
            </div>

            {!disabled && (
              <>
                <div
                  aria-hidden="true"
                  className="pointer-events-none absolute inset-0 rounded-sm bg-black/10 opacity-0 backdrop-blur-xs transition-opacity duration-300 ease-out group-focus-within:opacity-100 group-hover:opacity-100"
                />
                <div className="absolute inset-0 flex flex-col items-center justify-center gap-1 opacity-0 transition-opacity duration-200 ease-out group-focus-within:opacity-100 group-hover:opacity-100">
                  <Button
                    type="button"
                    data-media-field-action="true"
                    variant="outline"
                    onClick={handleChangeImage}
                    className="w-[100px] border-primary/10"
                  >
                    Change
                  </Button>
                  <Button
                    type="button"
                    data-media-field-action="true"
                    variant="default"
                    onClick={handleRemove}
                    className="w-[100px]"
                  >
                    Remove
                  </Button>
                </div>
              </>
            )}
          </CardContent>
          {footerMode !== 'none' && (
            <CardFooter className="grid w-full gap-0.5 px-4">
              {footerMode === 'url' ? (
                <div className="flex w-full min-w-0 items-center gap-x-2">
                  <div className="flex min-w-0 flex-1 items-center gap-x-2 text-muted-foreground">
                    <Link2 className="size-4 shrink-0" />
                    <Link
                      href={selectedMedia.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="min-w-0 truncate text-foreground underline-offset-4 hover:underline"
                    >
                      {selectedMedia.url}
                    </Link>
                  </div>
                  <Button
                    type="button"
                    data-media-field-action="true"
                    aria-label={hasCopiedMediaUrl ? 'Media URL copied' : 'Copy media URL'}
                    variant="ghost"
                    title={hasCopiedMediaUrl ? 'Copied' : 'Copy media URL'}
                    onClick={() => copyMediaUrl(selectedMedia.url)}
                    className="size-7 shrink-0"
                  >
                    {hasCopiedMediaUrl ? <Check className="text-foreground" /> : <Copy />}
                  </Button>
                </div>
              ) : (
                <span className="w-full truncate text-sm text-muted-foreground">
                  {selectedMedia.filename}
                </span>
              )}
            </CardFooter>
          )}
        </Card>

        <MediaGalleryDialog
          open={open}
          onOpenChange={setOpen}
          onSelect={handleSelect}
          mode="single"
          accept={accept}
        />
      </div>
    )
  }

  return (
    <MediaFieldEmptyState
      accept={accept}
      className={className}
      disabled={disabled}
      isRemovable={isRemovable}
      open={open}
      onOpenChange={setOpen}
      onSelect={handleSelect}
    />
  )
}
