'use client'

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

interface Faq {
    id: number
    title: string
    description: string
}

export default function AdminFaqPage() {
    const [faqs, setFaqs] = useState<Faq[]>([])
    const [loading, setLoading] = useState(false)
    const [showModal, setShowModal] = useState(false)
    const [editingFaq, setEditingFaq] = useState<Faq | null>(null)

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

    const fetchFaqs = async () => {
        setLoading(true)
        const res = await fetch('/api/admin/faq')
        const data: Faq[] = await res.json()
        setFaqs(data)
        setLoading(false)
    }

    const handleDelete = async (id: number) => {
        if (!confirm('Удалить вопрос?')) return
        const res = await fetch(`/api/admin/faq?id=${id}`, { method: 'DELETE' })
        if (res.ok) fetchFaqs()
    }

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

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

        if (res.ok) {
            fetchFaqs()
            setShowModal(false)
            setEditingFaq(null)
        }
    }

    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">
                        <table className="table table-dark table-bordered">
                            <thead>
                            <tr>
                                <th>Заголовок</th>
                                <th>Описание</th>
                                <th></th>
                            </tr>
                            </thead>
                            <tbody>
                            {faqs.map((faq) => (
                                <tr key={faq.id}>
                                    <td>{faq.title}</td>
                                    <td>{faq.description}</td>
                                    <td>
                                        <button
                                            className="btn btn-warning btn-sm me-2"
                                            onClick={() => {
                                                setEditingFaq(faq)
                                                setShowModal(true)
                                            }}
                                        >
                                            ✎
                                        </button>
                                        <button className="btn btn-danger btn-sm" onClick={() => handleDelete(faq.id)}>
                                            ✖
                                        </button>
                                    </td>
                                </tr>
                            ))}
                            </tbody>
                        </table>
                    </div>
                )}

                {showModal && (
                    <div className="modal d-block bg-dark bg-opacity-75" tabIndex={-1}>
                        <div className="modal-dialog">
                            <form className="modal-content bg-dark text-white" onSubmit={handleSubmit}>
                                <div className="modal-header">
                                    <h5 className="modal-title">{editingFaq ? 'Редактировать' : 'Добавить'} вопрос</h5>
                                    <button
                                        type="button"
                                        className="btn-close btn-close-white"
                                        onClick={() => {
                                            setShowModal(false)
                                            setEditingFaq(null)
                                        }}
                                    />
                                </div>
                                <div className="modal-body">
                                    <div className="mb-3">
                                        <label className="form-label">Заголовок</label>
                                        <input
                                            name="title"
                                            defaultValue={editingFaq?.title || ''}
                                            className="form-control"
                                            required
                                        />
                                    </div>
                                    <div className="mb-3">
                                        <label className="form-label">Описание</label>
                                        <textarea
                                            name="description"
                                            defaultValue={editingFaq?.description || ''}
                                            className="form-control"
                                            required
                                            rows={5}
                                        />
                                    </div>
                                </div>
                                <div className="modal-footer">
                                    <button
                                        type="button"
                                        className="btn btn-secondary"
                                        onClick={() => {
                                            setShowModal(false)
                                            setEditingFaq(null)
                                        }}
                                    >
                                        Отмена
                                    </button>
                                    <button type="submit" className="btn btn-success">
                                        Сохранить
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                )}
            </div>
        </div>
    )
}
