// Shared "save media to the photo library + show feedback" action. Wraps the
// pure `saveMediaToPhotos` service with the app's toast + haptic idiom so every
// entry point (long-press context menu, post overflow menu) behaves identically.

import { useToastController } from '@tamagui/toast'
import { useCallback } from 'react'
import { haptic } from 'src/lib/haptics'
import {
  type SaveInput,
  type SaveMediaKind,
  type SaveResult,
  saveMediaToPhotos,
} from 'src/lib/media/saveToPhotos'

export function useSaveMedia() {
  const toast = useToastController()

  return useCallback(
    async (
      input: SaveInput,
      displayKind: SaveMediaKind = 'image'
    ): Promise<SaveResult> => {
      // Downloads can take a moment (especially video) — give instant feedback.
      if (displayKind === 'video') {
        toast.show('Saving video…', { duration: 1500 })
      }
      const result = await saveMediaToPhotos(input)
      if (result.ok) {
        haptic.success()
        toast.show('Saved to Photos', { preset: 'success', duration: 2000 })
        return result
      }
      if (result.reason === 'unsupported') {
        haptic.warning()
        toast.show("This media can't be saved", { preset: 'error', duration: 2500 })
        return result
      }
      haptic.error()
      const message =
        result.reason === 'permission'
          ? 'Allow photo access in Settings to save'
          : result.reason === 'download'
            ? "Couldn't download media"
            : "Couldn't save to Photos"
      toast.show(message, { preset: 'error', duration: 2500 })
      return result
    },
    [toast]
  )
}
