'use client'

import { saveParserBackendService, UploadSaveResponse } from '@/services/SaveParserBackendService'
import { useState } from 'react'
import FormError from './FormError'

export enum GameEnum {
    EU4 = 'eu4',
    Stellaris = 'stellaris',
}

export default function SaveFileUploadingDialog() {
    const [error, setError] = useState<string | null>(null)
    const [selectedFile, setSelectedFile] = useState<File | null>(null)
    const [game, setGame] = useState<GameEnum>(GameEnum.EU4)
    const [uploadResult, setUploadResult] = useState<UploadSaveResponse | null>(null)

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files[0]) {
            setSelectedFile(e.target.files[0])
        }
    }

    const handleUpload = async () => {
        try {
            if (!selectedFile) return

            console.log('Uploading file:', selectedFile.name)
            const result = await saveParserBackendService.uploadSave(game, selectedFile)
            console.log('Got response:', result)
            setUploadResult(result)
        } catch (err: any) {
            console.error(err.message)
            setError(err.message)
        }
    }

    return (
        <div className="container mt-5" style={{ maxWidth: '500px' }}>
            <h3 className="mb-2 fw-semibold">Select game save file</h3>
            <FormError message={error} />

            <div className="mb-3">
                <label htmlFor="gameSelect" className="form-label">
                    Select Game
                </label>
                <select
                    id="gameSelect"
                    className="form-select"
                    value={game}
                    onChange={(e) => setGame(e.target.value as GameEnum)}
                >
                    {Object.values(GameEnum).map((value) => (
                        <option key={value} value={value}>
                            {value}
                        </option>
                    ))}
                </select>
            </div>

            <input type="file" className="form-control mb-3" onChange={handleFileChange} />
            <button className="btn btn-primary" onClick={handleUpload} disabled={!selectedFile}>
                Upload File
            </button>

            {selectedFile && (
                <div className="mt-3">
                    File: <strong>{selectedFile.name}</strong>
                </div>
            )}

            {uploadResult && (
                <div className="mt-3">
                    Save Id: <strong>{uploadResult.id}</strong>
                </div>
            )}
        </div>
    )
}
