'use client'

import { useEffect, useState, FormEvent } from 'react'
import AdminHeader from '@/components/AdminHeader'

const fields = ['name', 'description', 'cpu', 'ram', 'gpu', 'mouse', 'keyboard', 'headphones', 'monitor', 'bracket', 'chair'] as const

type Room = {
    id: number
    name: string
    description: string
    cpu?: string
    ram?: string
    gpu?: string
    mouse?: string
    keyboard?: string
    headphones?: string
    monitor?: string
    bracket?: string
    chair?: string
}

export default function AdminRoomsPage() {
    const [rooms, setRooms] = useState<Room[]>([])
    const [loading, setLoading] = useState(false)
    const [showModal, setShowModal] = useState(false)
    const [editingRoom, setEditingRoom] = useState<Room | null>(null)

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

    const fetchRooms = async () => {
        setLoading(true)
        const res = await fetch('/api/admin/rooms')
        const data: Room[] = await res.json()
        setRooms(data)
        setLoading(false)
    }

    const handleDelete = async (id: number) => {
        if (!confirm('Удалить комнату?')) return
        const res = await fetch(`/api/admin/rooms?id=${id}`, { method: 'DELETE' })
        if (res.ok) fetchRooms()
    }

    const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        const form = e.currentTarget
        const formData = new FormData(form)
        const payload = Object.fromEntries(formData.entries())

        const method = editingRoom ? 'PUT' : 'POST'

        const res = await fetch('/api/admin/rooms', {
            method,
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(editingRoom ? { ...editingRoom, ...payload } : payload)
        })

        if (res.ok) {
            fetchRooms()
            setShowModal(false)
            setEditingRoom(null)
        }
    }

    const standardRooms = rooms.filter(r => r.name.toLowerCase() !== 'ps')
    const psRooms = rooms.filter(r => r.name.toLowerCase() === 'ps')

    return (
        <div>
            <AdminHeader />
            <div className="container py-5 text-light">
                <div className="d-flex justify-content-between align-items-center mb-4">
                    <h2 className="fs-1">Железо</h2>
                    <button className="btn btn-success" onClick={() => setShowModal(true)}>
                        + Добавить комнату
                    </button>
                </div>

                {loading ? <p>Загрузка...</p> : (
                    <>
                        <div className="table-responsive mb-5">
                            <h4 className="mb-3">Стандартные комнаты</h4>
                            <table className="table table-dark table-bordered">
                                <thead>
                                <tr>
                                    {fields.map(f => <th key={f}>{f}</th>)}
                                    <th></th>
                                </tr>
                                </thead>
                                <tbody>
                                {standardRooms.map((room) => (
                                    <tr key={room.id}>
                                        {fields.map(f => <td key={f}>{room[f]}</td>)}
                                        <td>
                                            <button className="btn btn-warning btn-sm me-2" onClick={() => { setEditingRoom(room); setShowModal(true) }}>✎</button>
                                            <button className="btn btn-danger btn-sm" onClick={() => handleDelete(room.id)}>✖</button>
                                        </td>
                                    </tr>
                                ))}
                                </tbody>
                            </table>
                        </div>

                        {psRooms.length > 0 && (
                            <div className="table-responsive">
                                <h4 className="mb-3">Консольные комнаты (PS)</h4>
                                <table className="table table-dark table-bordered">
                                    <thead>
                                    <tr>
                                        <th>name</th>
                                        <th>description</th>
                                        <th>attachment</th>
                                        <th>gamepad</th>
                                        <th>tv</th>
                                        <th></th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {psRooms.map((room) => (
                                        <tr key={room.id}>
                                            <td>{room.name}</td>
                                            <td>{room.description}</td>
                                            <td>{room.cpu}</td>
                                            <td>{room.ram}</td>
                                            <td>{room.gpu}</td>
                                            <td>
                                                <button className="btn btn-warning btn-sm me-2" onClick={() => { setEditingRoom(room); setShowModal(true) }}>✎</button>
                                                <button className="btn btn-danger btn-sm" onClick={() => handleDelete(room.id)}>✖</button>
                                            </td>
                                        </tr>
                                    ))}
                                    </tbody>
                                </table>
                            </div>
                        )}
                    </>
                )}

                {showModal && (
                    <div className="modal d-block bg-dark bg-opacity-75" tabIndex={-1}>
                        <div className="modal-dialog modal-dialog-scrollable">
                            <form className="modal-content bg-dark text-white" onSubmit={handleSubmit}>
                                <div className="modal-header">
                                    <h5 className="modal-title">{editingRoom ? 'Редактировать' : 'Добавить'} комнату</h5>
                                    <button type="button" className="btn-close btn-close-white" onClick={() => { setShowModal(false); setEditingRoom(null) }} />
                                </div>
                                <div className="modal-body">
                                    {fields.map(field => (
                                        <div className="mb-3" key={field}>
                                            <label className="form-label">{field}</label>
                                            <input
                                                name={field}
                                                defaultValue={editingRoom?.[field] || ''}
                                                className="form-control"
                                                required={field === 'name'}
                                            />
                                        </div>
                                    ))}
                                </div>
                                <div className="modal-footer">
                                    <button type="button" className="btn btn-secondary" onClick={() => { setShowModal(false); setEditingRoom(null) }}>
                                        Отмена
                                    </button>
                                    <button type="submit" className="btn btn-success">Сохранить</button>
                                </div>
                            </form>
                        </div>
                    </div>
                )}
            </div>
        </div>
    )
}
