import {
  useCallback,
  useEffect,
  useMemo,
  useState,
} from 'react';

import { rpc } from '@/api/request';
import { Lang } from '@/lang/Lang';
import useAppConfigStore from '@/stores/appConfig';
import { copyTextToClipboard } from '@/utils/helpers';

import type { ItemDataProps } from '../../../types';
import { selectFile } from '../../utils/selectFile';
import {
  clearImageValue,
  getImageUrl,
  haveImageValue,
  mapImageUploadValue,
} from '../imageHelpers';

export function useFileDataImage(props: ItemDataProps) {
  const [localValue, setLocalValue] = useState(props.getValue());
  const [uploading, setUploading] = useState(false);

  const structureType = props.structure.type ?? 'fileImage';

  useEffect(() => {
    props.setValue(localValue);
  }, [localValue]);

  const url = useMemo(() => getImageUrl(localValue, structureType), [localValue, structureType]);
  const hasValue = useMemo(() => haveImageValue(localValue, structureType), [localValue, structureType]);

  const { isMobile } = useAppConfigStore();
  const col = props.structure?.col ?? 24;
  const buttonTitle = Lang.key('select_image');

  const delFile = useCallback(() => {
    setLocalValue(clearImageValue(structureType));
  }, [structureType]);


  const uploadBase64Request = useCallback((base64: string) => {

    if (!base64) {
      return;
    }
    const formData = new FormData();
    formData.append('file', base64);
    setUploading(true);
    rpc
      .imageUpload(formData)
      .then((json) => {
        if (json) {
          setLocalValue(mapImageUploadValue(json, structureType));
        }
      })
      .finally(() => {
        setUploading(false);
      });
  }, [structureType]);

  const uploadRequest = useCallback((file: File) => {
    if (!file) {
      return;
    }
    const formData = new FormData();
    formData.append('file', file);
    setUploading(true);
    rpc
      .imageUpload(formData)
      .then((json) => {
        if (json) {
          setLocalValue(mapImageUploadValue(json, structureType));
        }
      })
      .finally(() => {
        setUploading(false);
      });
  }, [structureType]);



  const onUploadNewFile = useCallback(() => {
    selectFile('image/*').then((file) => {
      if (file) {
        uploadRequest(file);
      }
    });
  }, [uploadRequest]);

  const onCopyLink = useCallback(() => {
    copyTextToClipboard(url);
  }, [url]);

  return {
    url,
    hasValue,
    uploading,
    buttonTitle,
    isMobile,
    uploadRequest,
    uploadBase64Request,
    col,
    delFile,
    onUploadNewFile,
    onCopyLink,
  };
}
