'use client'

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

type Price = {
    id: number
    game_type: 'ПК' | 'PS'
    room_type: string
    day_type: string
    hour_1: number
    hour_3: number
    hour_5: number
    night: number
}

export default function AdminPricesPage() {
    const [prices, setPrices] = useState<Price[]>([])
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState('')
    const [editRow, setEditRow] = useState<Price | null>(null)
    const [showModal, setShowModal] = useState(false)

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

    const fetchPrices = async () => {
        setLoading(true)
        try {
            const res = await fetch('/api/admin/price')
            const data: Price[] = await res.json()
            setPrices(data)
        } catch {
            setError('Ошибка при загрузке тарифов')
        } finally {
            setLoading(false)
        }
    }

    const handleEditClick = (row: Price) => {
        setEditRow(row)
        setShowModal(true)
    }

    const handleSave = async (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        const form = e.currentTarget
        const formData = new FormData(form)
        const updated = Object.fromEntries(formData.entries()) as Record<string, string>

        const res = await fetch('/api/admin/price', {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ...editRow, ...updated })
        })

        if (res.ok) {
            await fetchPrices()
            setShowModal(false)
            setEditRow(null)
        } else {
            alert('Ошибка при сохранении')
        }
    }

    return (
        <div>
            <AdminHeader />
            <div className="container py-5 text-light">
                <h2 className="mb-4 fs-1 text-center">Цены на ПК</h2>

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

                <div className="table-responsive">
                    <table className="table table-dark table-bordered align-middle text-center">
                        <thead>
                        <tr>
                            <th>Тип игры</th>
                            <th>Тип комнаты</th>
                            <th>Тип дня</th>
                            <th>1 час</th>
                            <th>3 часа</th>
                            <th>5 часов</th>
                            <th>Ночь</th>
                            <th></th>
                        </tr>
                        </thead>
                        <tbody>
                        {prices.map((row, idx) =>
                            row.game_type === 'ПК' ? (
                                <tr key={idx}>
                                    <td>{row.game_type}</td>
                                    <td>{row.room_type}</td>
                                    <td>{row.day_type}</td>
                                    <td>{row.hour_1}</td>
                                    <td>{row.hour_3}</td>
                                    <td>{row.hour_5}</td>
                                    <td>{row.night}</td>
                                    <td>
                                        <button className="btn btn-sm btn-warning" onClick={() => handleEditClick(row)}>
                                            ✎ Редактировать
                                        </button>
                                    </td>
                                </tr>
                            ) : null
                        )}
                        </tbody>
                    </table>
                </div>

                <h2 className="mb-4 fs-1 text-center">Цены на PS</h2>

                <div className="table-responsive">
                    <table className="table table-dark table-bordered align-middle text-center">
                        <thead>
                        <tr>
                            <th>Тип игры</th>
                            <th>Тип комнаты</th>
                            <th>Тип дня</th>
                            <th>1 час</th>
                            <th>3 часа</th>
                            <th>5 часов</th>
                            <th>Ночь</th>
                            <th></th>
                        </tr>
                        </thead>
                        <tbody>
                        {prices.map((row, idx) =>
                            row.game_type === 'PS' ? (
                                <tr key={idx}>
                                    <td>{row.game_type}</td>
                                    <td>{row.room_type}</td>
                                    <td>{row.day_type}</td>
                                    <td>{row.hour_1}</td>
                                    <td>{row.hour_3}</td>
                                    <td>{row.hour_5}</td>
                                    <td>{row.night}</td>
                                    <td>
                                        <button className="btn btn-sm btn-warning" onClick={() => handleEditClick(row)}>
                                            ✎ Редактировать
                                        </button>
                                    </td>
                                </tr>
                            ) : null
                        )}
                        </tbody>
                    </table>
                </div>

                {showModal && editRow && (
                    <div className="modal d-block bg-dark bg-opacity-75" tabIndex={-1}>
                        <div className="modal-dialog modal-dialog-centered">
                            <form className="modal-content bg-dark text-white" onSubmit={handleSave}>
                                <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">
                                    {['hour_1', 'hour_3', 'hour_5', 'night'].map((field) => (
                                        <div className="mb-3" key={field}>
                                            <label className="form-label">{field.replace('_', ' ')}:</label>
                                            <input
                                                name={field}
                                                type="number"
                                                step="0.01"
                                                defaultValue={editRow[field as keyof Price]?.toString() || ''}
                                                className="form-control"
                                                required
                                            />
                                        </div>
                                    ))}
                                </div>
                                <div className="modal-footer">
                                    <button className="btn btn-secondary" type="button" onClick={() => setShowModal(false)}>
                                        Отмена
                                    </button>
                                    <button className="btn btn-success" type="submit">
                                        Сохранить
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                )}
            </div>
        </div>
    )
}
