'use client'

import { FormEvent, useEffect, useState } from 'react'
import AdminHeader from "@/components/AdminHeader"
import Image from "next/image"

type Game = {
    id: number
    title: string
    image_url: string
    platform: string
}

export default function AdminGamesPage() {
    const [games, setGames] = useState<Game[]>([])
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState('')
    const [showModal, setShowModal] = useState(false)

    useEffect(() => {
        fetchGames()
    }, [])

    const fetchGames = async () => {
        setLoading(true)
        try {
            const res = await fetch('/api/admin/games')
            const data: Game[] = await res.json()
            setGames(data)
        } catch {
            setError('Ошибка при загрузке игр')
        } finally {
            setLoading(false)
        }
    }

    const handleDelete = async (id: number) => {
        const confirmed = confirm('Удалить игру?')
        if (!confirmed) return

        const res = await fetch(`/api/admin/games?id=${id}`, { method: 'DELETE' })
        if (res.ok) {
            setGames((prev) => prev.filter((g) => g.id !== id))
        } else {
            alert('Ошибка при удалении')
        }
    }

    const handleAddGame = async (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        const form = e.currentTarget
        const formData = new FormData(form)

        const res = await fetch('/api/admin/games/upload', {
            method: 'POST',
            body: formData,
        })

        if (res.ok) {
            const added: Game = await res.json()
            setGames((prev) => [...prev, added])
            setShowModal(false)
        } else {
            alert('Ошибка при добавлении игры')
        }
    }

    const imageLoader = ({ src }: { src: string }) => `/api/uploads/games/${src}`

    return (
        <div>
            <AdminHeader />
            <div className="container py-5 text-light">
                <div className="text-center mb-5">
                    <button className="btn btn-primary" onClick={() => setShowModal(true)}>
                        Добавить новую игру
                    </button>
                </div>

                <h2 className="mb-4 fs-1 text-center">Список игр</h2>

                {loading && <p>Загрузка...</p>}
                {error && <p className="text-danger">{error}</p>}

                <div className="row row-cols-1 row-cols-md-4 g-4">
                    {games.map((game) => (
                        <div key={game.id} className="col">
                            <div className="card bg-dark text-white h-100">
                                {game.image_url && (
                                    <Image
                                        loader={() => imageLoader({ src: game.image_url })}
                                        src={`/api/uploads/games/${game.image_url}`}
                                        alt={game.title}
                                        className="card-img-top"
                                        width={400}
                                        height={160}
                                        style={{ objectFit: 'cover', width: '100%', height: 160 }}
                                    />
                                )}
                                <div className="card-body">
                                    <h5 className="card-title">{game.title}</h5>
                                    <p className="card-text">Платформа: {game.platform}</p>
                                    <button className="btn btn-danger" onClick={() => handleDelete(game.id)}>
                                        Удалить
                                    </button>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>

                {showModal && (
                    <div className="modal d-block bg-black bg-opacity-75" tabIndex={-1} role="dialog">
                        <div className="modal-dialog modal-dialog-centered" role="document">
                            <form className="modal-content bg-dark text-white" onSubmit={handleAddGame} encType="multipart/form-data">
                                <div className="modal-header">
                                    <h5 className="modal-title">Новая игра</h5>
                                    <button type="button" className="btn-close btn-close-white" onClick={() => setShowModal(false)} />
                                </div>
                                <div className="modal-body">
                                    <div className="mb-3">
                                        <label className="form-label">Название</label>
                                        <input name="title" type="text" className="form-control" required />
                                    </div>

                                    <div className="mb-3">
                                        <label className="form-label">Платформа</label>
                                        <select name="platform" className="form-select" defaultValue="pc">
                                            <option value="pc">PC</option>
                                            <option value="ps">PS</option>
                                        </select>
                                    </div>

                                    <div className="mb-3">
                                        <label className="form-label">Изображение</label>
                                        <input name="image" type="file" accept="image/*" className="form-control" required />
                                    </div>
                                </div>
                                <div className="modal-footer">
                                    <button type="button" className="btn btn-secondary" onClick={() => setShowModal(false)}>
                                        Отмена
                                    </button>
                                    <button type="submit" className="btn btn-success">
                                        Сохранить
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                )}
            </div>
        </div>
    )
}
