// components/shared/ImageUploadFile.tsx
'use client'

import { ChangeEvent, useEffect, useMemo, useState } from 'react'
import { LinearProgress, Button } from '@mui/material'
import { useUpdateImage } from '@/hooks'
import type { ControllerRenderProps } from 'react-hook-form'
import { SetSrc } from '@/utils/set-src'

type Props = {
  label: string
  path: string // e.g. section_key
  field: ControllerRenderProps<any, string>
}

export default function ImageUploadFile({ label, path, field }: Props) {
  const { mutateAsync, isPending } = useUpdateImage()
  const [pickedName, setPickedName] = useState<string | null>(null)
  const [localPreview, setLocalPreview] = useState<string | null>(null) // object URL

  // Always show either the local preview or the current server path
  const previewSrc = useMemo(() => localPreview || SetSrc(field.value), [localPreview, field.value])

  useEffect(() => {
    // cleanup object URL when component unmounts or new file picked
    return () => {
      if (localPreview) URL.revokeObjectURL(localPreview)
    }
  }, [localPreview])

  const onPick = async (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    setPickedName(file.name)

    // 1) show instant local preview
    const objectUrl = URL.createObjectURL(file)
    setLocalPreview(objectUrl)

    // 2) upload using FormData
    const fd = new FormData()
    fd.append('image', file)
    fd.append('path', path)

    const res = await mutateAsync(fd)
    const uploadedPath = res?.data?.image_path || ''

    // 3) swap to server path with cache-buster to avoid stale cache
    const cacheBusted = uploadedPath ? `${uploadedPath}?t=${Date.now()}` : ''
    field.onChange(cacheBusted)

    // free the local object URL (optional small delay to avoid flicker)
    setTimeout(() => {
      if (objectUrl) URL.revokeObjectURL(objectUrl)
      setLocalPreview(null)
    }, 0)
  }

  return (
    <div className='flex flex-col gap-2'>
      <div className='flex items-center gap-3'>
        <label className='text-sm font-medium'>{label}</label>
        <input type='file' accept='image/*' onChange={onPick} />
      </div>

      {isPending && <LinearProgress />}

      {previewSrc ? (
        <img src={previewSrc} alt={label} className='mt-2 h-64 w-full rounded-md object-contain' />
      ) : (
        <p className='text-xs text-muted-foreground'>No image set</p>
      )}

      {field.value && (
        <Button size='medium' variant='outlined' onClick={() => field.onChange('')} className='mt-2'>
          Remove
        </Button>
      )}
    </div>
  )
}
