import React, {FC, useState} from "react";
import {__} from "../../globals";
import {Text} from "../fields/Text";
import {useAtom} from "jotai/index";
import {CurrentDashboardSectionIdAtom, CustomPresetSourceAtom} from "../atoms";
import {Button} from "../cards/Button";
import {useNodesStore} from "../store";
import {useSetAtom} from "jotai";
import {TreeDashboardSection} from "../TreeDashboardSections";

export type CustomPresetProps = {
}

export const CustomPreset: FC<CustomPresetProps> = ({}) => {
    const [preset, setPreset] = useAtom(CustomPresetSourceAtom)
    const setDashboardSection = useSetAtom(CurrentDashboardSectionIdAtom)
    const [error, setError] = useState('')
    const importFromSource = useNodesStore(store => store.importFromSource)

    return <div className="w-100 flex flex-col items-center justify-center gap-y-5">
        <h1 className="text-5x font-medium text-gray-800">{__('Import a custom preset')}</h1>
        <Text  id={'customPreset'}
              fullWidth={true}
              value={preset}
              onChange={(value) => {
                setPreset(value)
              }}
              placeholder={__('Paste a custom preset code here to import')}
        />
        <div className="w-full flex flex-col gap-1">
            <Button preset={preset ? 'blue' : 'gray'} onClick={() => {
                try {
                    JSON.parse(preset)
                } catch (e) {
                    setError('Cannot import preset. Preset code may be corrupted or have an incompatible format.')
                    return
                }
                // no errors, its valid JSON
                importFromSource(preset)
                setDashboardSection(TreeDashboardSection.Offers)
            }}>
                Import
            </Button>
            {error && (<p className="text-gray-500 text-smaller-1 leading-4">{error}</p>)}
        </div>
    </div>
}
