import React, { useEffect, useState } from 'react';
import { EditableMetadata } from '@theorchard/suite-components';
import { useUpdateSapProfitCenter } from 'src/apollo/mutations/reference-sap-profit-center';
import { useEditableDisplayNameContext } from 'src/components/reference-sap-profit-center-edit/editable-display-name-context';
import './styles.scss';

interface EditableDisplayNameCellProps {
    rowData: {
        referenceSapProfitCenterId: string;
        displayName: string;
    };
}

export const EditableDisplayNameCell: React.FC<
    EditableDisplayNameCellProps
> = ({ rowData }) => {
    const { debouncedRefetch, page, pageSize } =
        useEditableDisplayNameContext();

    const updateSapProfitCenter = useUpdateSapProfitCenter();
    const targetId = rowData.referenceSapProfitCenterId;
    const [localValue, setLocalValue] = useState<string>(rowData.displayName);
    const [processing, setProcessing] = useState<{
        type: 'loading' | 'success';
        message?: string;
    }>();
    const [validationError, setValidationError] = useState<string>('');

    useEffect(() => {
        setLocalValue(rowData.displayName);
    }, [rowData.displayName]);

    const handleConfirm = async (newValue: string) => {
        setProcessing({ type: 'loading', message: 'Saving...' });
        setValidationError('');
        setLocalValue(newValue);
        try {
            await updateSapProfitCenter({
                variables: {
                    referenceSapProfitCenterId: targetId,
                    displayName: newValue,
                },
            });
            debouncedRefetch(page, pageSize);
            setProcessing({ type: 'success', message: 'Saved successfully!' });
            setTimeout(() => setProcessing(undefined), 2500);
        } catch (error) {
            console.log('rowData.displayName', rowData.displayName);
            setValidationError('Failed to save changes.');
            setProcessing(undefined);
            setLocalValue(rowData.displayName);
        }
    };

    return (
        <div style={{ whiteSpace: 'pre-wrap' }} className="EditDisplayName">
            <EditableMetadata
                label={''}
                value={localValue}
                onConfirm={handleConfirm}
                validationFn={value => value.trim().length > 0}
                validationError={'Value cannot be empty'}
                processing={processing}
            />
            <div className="DisplayNameError">{validationError}</div>
        </div>
    );
};

export default EditableDisplayNameCell;
