import React, { FC, useEffect, useState } from 'react';
import { View } from 'react-native';

import Button from '../../../../../../../components/Button/Button';
import Loader from '../../../../../../../components/Loader/Loader';
import Modal from '../../../../../../../components/Modal/Modal';
import TextFieldSelect from '../../../../../../../components/TextField/TextFieldSelect';
import { EXPORT_FORMATS } from '../../../../../../../constants/custom';
import { useUserInfo } from '../../../../../../../hooks/useStorage';
import { useExportPersonGet } from '../../../../../../../hooks/useTeplates';

type props = {
  isVisible: boolean;
  setIsVisible: (value: boolean) => void;
  exportId: string;
};

const TemplateDownloadModal: FC<props> = ({ isVisible, setIsVisible, exportId }) => {
  const [userInfo] = useUserInfo();
  const [format, setFormat] = useState(EXPORT_FORMATS[0]);

  const { mutate: downloadExport, isLoading: isDownloading } = useExportPersonGet(
    userInfo.token,
    () => setIsVisible(false),
  );

  useEffect(() => {
    if (isVisible) {
      setFormat(EXPORT_FORMATS[0]);
    }
  }, [isVisible]);

  return (
    <Modal
      title="Vyberte formát exportu"
      isVisible={isVisible}
      setIsVisible={setIsVisible}
      buttons={
        <View className="flex-row">
          {!isDownloading && (
            <Button classNames="px-4" variant="text" onPress={() => setIsVisible(false)}>
              Zrušit
            </Button>
          )}
          <Button
            classNames="pl-4"
            disabled={isDownloading}
            variant="text"
            onPress={() => {
              downloadExport({ exportId, format });
            }}
          >
            {isDownloading ? 'Stahuji...' : 'Stáhnout'}
          </Button>
        </View>
      }
    >
      {!isDownloading ? (
        <View className="mb-4">
          <TextFieldSelect
            title="Formát exportu"
            items={EXPORT_FORMATS}
            value={format}
            setValue={setFormat}
          />
        </View>
      ) : (
        <Loader />
      )}
    </Modal>
  );
};

export default TemplateDownloadModal;
