import type { FC } from 'react';
import React, { useState, useEffect, useRef } from 'react';
import { BsModal, Button } from '@theorchard/suite-components';
import { GlyphIcon } from '@theorchard/suite-icons';
import { INCORRECT_ARTIST_INFO_STATE } from '../../../constants';
import { formatMessage } from '../../../locale';
import { makeCancelable } from '../../../utils/cancelablePromise';
import IncorrectArtistSubmitSuccessModal from './incorrectArtistSubmitSuccessModal';
import type { CancelablePromise } from '../../../utils/cancelablePromise';

const CLASS_NAME = 'IncorrectArtistInfoModal';
const { DEFAULT, SUBMITTING, SUBMIT_SUCCESS } = INCORRECT_ARTIST_INFO_STATE;

interface Props {
    onClose: () => void;
    onSubmit: (info: string, currentName: string, newName: string) => Promise<unknown>;
    currentArtistName: string;
}

const IncorrectArtistInfoModal: FC<Props> = ({ onClose, onSubmit, currentArtistName }) => {
    const [infoText, setInfoText] = useState('');
    const [newArtistName, setNewArtistName] = useState('');
    const [showArtistNameUpdate, setShowArtistNameUpdate] = useState(false);
    const [modalState, setModalState] = useState(DEFAULT);
    const [show, setShow] = useState(true);
    const submitPromise = useRef<CancelablePromise>();

    useEffect(() => () => submitPromise.current?.cancel(), []);

    const handleClose = () => {
        onClose();
        setShow(false);
    };

    const handleInfoChange = ({ target: { value } }: React.ChangeEvent<HTMLTextAreaElement>) =>
        setInfoText(value);

    const handleNewArtistNameChange = ({
        target: { value },
    }: React.ChangeEvent<HTMLInputElement>) => setNewArtistName(value);

    const handleSubmit = async () => {
        setModalState(SUBMITTING);
        submitPromise.current = makeCancelable(
            onSubmit(infoText, currentArtistName, newArtistName)
        );
        return await submitPromise.current.promise
            .then(() => setModalState(SUBMIT_SUCCESS))
            .catch(handleClose);
    };

    const handleShowArtistNameUpdate = () => {
        setShowArtistNameUpdate((prevState) => !prevState);
    };

    if (modalState === SUBMIT_SUCCESS)
        return <IncorrectArtistSubmitSuccessModal onClose={handleClose} />;

    return (
        <BsModal className={CLASS_NAME} show={show} onHide={handleClose}>
            <BsModal.Header>{formatMessage('incorrectArtistInfo.header')}</BsModal.Header>
            <BsModal.Body>
                <div className={`${CLASS_NAME}-content`}>
                    <div className={`${CLASS_NAME}-content-info`}>
                        {formatMessage('incorrectArtistInfo.infoLine1')}
                        <br />
                        {formatMessage('incorrectArtistInfo.infoLine2')}
                    </div>
                    <textarea
                        disabled={modalState === INCORRECT_ARTIST_INFO_STATE.SUBMITTING}
                        className={`form-control ${CLASS_NAME}-content-textarea`}
                        placeholder={formatMessage('incorrectArtistInfo.placeholder')}
                        rows={5}
                        onChange={handleInfoChange}
                        value={infoText}
                    />
                    <Button
                        className={`${CLASS_NAME}-content-link`}
                        variant="link"
                        onClick={handleShowArtistNameUpdate}
                    >
                        I need to update this artist name
                    </Button>
                    {!showArtistNameUpdate && <GlyphIcon name="caretDown" size={12} />}
                    {showArtistNameUpdate && <GlyphIcon name="caretUp" size={12} />}
                    {showArtistNameUpdate && (
                        <div className={`${CLASS_NAME}-content-update-artist`}>
                            <h5 className={`${CLASS_NAME}-content-update-artist-title`}>
                                Request Artist Name Update
                            </h5>
                            <label
                                className={`${CLASS_NAME}-content-update-artist-label`}
                                htmlFor="current-artist-name"
                            >
                                CURRENT ARTIST NAME
                                <input
                                    id="current-artist-name"
                                    type="text"
                                    className={`form-control ${CLASS_NAME}-content-update-artist-input`}
                                    value={currentArtistName}
                                    disabled
                                />
                            </label>
                            <label
                                className={`${CLASS_NAME}-content-update-artist-label`}
                                htmlFor="new-artist-name"
                            >
                                UPDATED ARTIST NAME
                                <input
                                    id="new-artist-name"
                                    type="text"
                                    className={`form-control ${CLASS_NAME}-content-update-artist-input`}
                                    placeholder="Please enter new artist name"
                                    onChange={handleNewArtistNameChange}
                                    value={newArtistName}
                                />
                            </label>
                        </div>
                    )}
                </div>
            </BsModal.Body>
            <BsModal.Footer>
                <div className={`${CLASS_NAME}-footer`}>
                    <Button onClick={handleClose}>
                        {formatMessage('incorrectArtistInfo.cancel')}
                    </Button>
                    <Button
                        className={`${CLASS_NAME}-submit`}
                        variant="primary"
                        onClick={handleSubmit}
                        disabled={modalState === SUBMITTING || (!infoText && !newArtistName)}
                    >
                        {formatMessage('incorrectArtistInfo.submit')}
                    </Button>
                </div>
            </BsModal.Footer>
        </BsModal>
    );
};

export default IncorrectArtistInfoModal;
