import { useRef, useState } from 'react'
import { Film, X, Upload } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { apiOrigin } from '@/lib/api/client'
import { Progress } from '@/components/ui/progress'

function buildVideoUrl(value: string | undefined | null) {
  if (!value) return null
  if (value.startsWith('http')) return value
  const cleanPath = value.replace(/^\/+/, '').replace(/^storage\//, '')
  return `${apiOrigin}/${cleanPath}`
}

export function VideoUploadField({
  value,
  onChange,
  pendingFileName,
  isSaving,
  uploadProgress,
  onFileSelect,
  onClearSelection,
  label = 'Video',
}: {
  value: string
  onChange: (value: string) => void
  pendingFileName: string | null
  isSaving: boolean
  uploadProgress: number
  onFileSelect: (file: File) => void
  onClearSelection: () => void
  label?: string
}) {
  const inputRef = useRef<HTMLInputElement | null>(null)
  const [dragOver, setDragOver] = useState(false)
  const videoUrl = buildVideoUrl(value)

  const handleFile = (file: File) => {
    if (file.size > 100 * 1024 * 1024) {
      alert('Video boyutu en fazla 100MB olabilir.')
      return
    }
    onFileSelect(file)
  }

  return (
    <div className='space-y-4 rounded-3xl border border-border/70 bg-card p-5 shadow-sm'>
      <div className='space-y-1'>
        <p className='text-sm font-semibold'>{label}</p>
        <p className='text-sm text-muted-foreground'>
          MP4, WEBM, MOV — maks. 100MB
        </p>
      </div>

      <input
        ref={inputRef}
        type='file'
        accept='video/mp4,video/webm,video/quicktime,video/x-msvideo,video/x-matroska'
        className='hidden'
        onChange={(event) => {
          const file = event.target.files?.[0]
          if (file) handleFile(file)
          event.currentTarget.value = ''
        }}
      />

      <div className='space-y-3'>
        <div
          className={`relative mx-auto w-full overflow-hidden rounded-3xl border-2 border-dashed transition ${
            dragOver
              ? 'border-primary bg-primary/5'
              : 'border-border/70 bg-muted/20'
          }`}
          onDragOver={(e) => {
            e.preventDefault()
            setDragOver(true)
          }}
          onDragLeave={() => setDragOver(false)}
          onDrop={(e) => {
            e.preventDefault()
            setDragOver(false)
            const file = e.dataTransfer.files[0]
            if (file) handleFile(file)
          }}
        >
          {videoUrl && !pendingFileName ? (
            <div className='relative'>
              <video
                src={videoUrl}
                className='w-full max-h-[260px] object-contain bg-black/5'
                controls
                muted
                preload='metadata'
              />
              <div className='absolute top-3 right-3 flex gap-2'>
                <Button
                  type='button'
                  size='icon'
                  className='size-9 rounded-full bg-background/95 text-foreground shadow-sm backdrop-blur hover:bg-background'
                  onClick={() => inputRef.current?.click()}
                  disabled={isSaving}
                >
                  <Upload className='size-4' />
                </Button>
                <Button
                  type='button'
                  variant='outline'
                  size='icon'
                  className='size-9 rounded-full bg-background/95 shadow-sm backdrop-blur'
                  onClick={() => {
                    onChange('')
                    onClearSelection()
                  }}
                  disabled={isSaving}
                >
                  <X className='size-4' />
                </Button>
              </div>
            </div>
          ) : (
            <button
              type='button'
              onClick={() => inputRef.current?.click()}
              disabled={isSaving}
              className='flex w-full flex-col items-center justify-center gap-3 px-6 py-10 text-muted-foreground transition hover:text-foreground disabled:pointer-events-none disabled:opacity-60'
            >
              <div className='rounded-full border border-border/70 bg-background p-3'>
                <Film className='size-5' />
              </div>
              <div className='space-y-1 text-center'>
                <p className='text-sm font-medium'>
                  {dragOver ? 'Videoyu bırakın' : 'Video seç veya sürükle'}
                </p>
                <p className='text-xs text-muted-foreground'>
                  MP4, WEBM, MOV — maks. 100MB
                </p>
              </div>
            </button>
          )}
        </div>

        {isSaving && pendingFileName && (
          <div className='space-y-2'>
            <Progress value={uploadProgress} className='h-2' />
            <p className='text-center text-xs text-muted-foreground'>
              Yükleniyor: %{uploadProgress}
            </p>
          </div>
        )}

        {pendingFileName && !isSaving ? (
          <div className='rounded-2xl border border-sky-200 bg-sky-50 px-3 py-2 text-center text-sm text-sky-900'>
            <span className='font-medium'>{pendingFileName}</span> seçildi.
          </div>
        ) : !value && !pendingFileName ? (
          <p className='text-center text-xs text-muted-foreground'>
            Alana tıklayarak veya sürükleyerek video yükleyebilirsiniz.
          </p>
        ) : null}
      </div>
    </div>
  )
}
