/**
 * Restore Modal — confirmation before overwriting current file
 * Ball Studios <https://git.balls.studio>
 */

import React, { useState } from 'react';
import http from '@/api/http';

interface Props {
    serverUuid: string;
    revision: { id: number; revision_number: number; change_summary: string };
    onClose: () => void;
    onRestored: () => void;
}

export default function RestoreModal({ serverUuid, revision, onClose, onRestored }: Props) {
    const [loading, setLoading] = useState(false);
    const [error, setError]     = useState<string | null>(null);

    const handleRestore = async () => {
        setLoading(true);
        setError(null);
        try {
            await http.post(`/api/client/servers/${serverUuid}/addons/files/revisions/${revision.id}/restore`);
            onRestored();
        } catch (e: any) {
            setError(e?.response?.data?.errors?.[0]?.detail ?? 'Restore failed.');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className='addon-modal-overlay' role='dialog' aria-modal='true'>
            <div className='addon-modal'>
                <div className='addon-modal-icon'>🔄</div>
                <h3 className='addon-modal-title'>Restore Revision #{revision.revision_number}?</h3>
                <p className='addon-modal-body'>
                    This will overwrite the current file with revision #{revision.revision_number}.<br />
                    <em>{revision.change_summary}</em>
                </p>
                {error && <p className='addon-error'>{error}</p>}
                <div className='addon-modal-actions'>
                    <button className='addon-btn addon-btn-secondary' onClick={onClose} disabled={loading}>Cancel</button>
                    <button className='addon-btn addon-btn-primary' onClick={handleRestore} disabled={loading}>
                        {loading ? 'Restoring…' : 'Restore'}
                    </button>
                </div>
            </div>
        </div>
    );
}
