'use client'

import { useEffect, useState } from 'react'
import AdminHeader from "@/components/AdminHeader"
import {
    AdminContainer,
    AdminContent,
    PageTitle,
    FiltersContainer,
    FilterGroup,
    FilterLabel,
    FilterInput,
    FilterSelect,
    RoomCard,
    RoomCardHeader,
    RoomCardTitle,
    RoomCapacity,
    TimeGrid,
    TimeSlot,
    TimeSlotHeader,
    TimeSlotTime,
    TimeSlotCount,
    TimeSlotBookings,
    BookingBadge,
    BookingsList,
    BookingCard,
    BookingCardHeader,
    BookingCardInfo,
    BookingCardTitle,
    BookingCardMeta,
    BookingCardActions,
    StatusSelect,
    DeleteButton,
    EmptyState,
    EmptyStateIcon,
    EmptyStateText,
    LoadingSpinner,
    Spinner,
    SectionTitle,
    AddButton,
    ModalOverlay,
    ModalContent,
    ModalHeader,
    ModalTitle,
    ModalCloseButton,
    ModalBody,
    FormRow,
    FormLabel,
    FormInput as StyledFormInput,
    FormSelect as StyledFormSelect,
    ModalFooter,
    CancelButton,
    SubmitButton,
    ErrorMessage
} from "@/styles/admin.styled"

type Booking = {
    id: number
    type: string
    room: string
    date_time: string
    time_slot: string
    name: string
    game: string | null
    contact: string
    contact_method: string | null
    status: 'pending' | 'confirmed' | 'cancelled'
    created_at: string
}

const ROOM_NAMES: Record<string, string> = {
    'solo': 'Solo',
    'duo': 'Duo',
    'trio': 'Trio',
    'bootcamp 5': 'Bootcamp 5',
    'bootcamp 6': 'Bootcamp 6',
}

const ROOM_CAPACITY: Record<string, number> = {
    'solo': 5,
    'duo': 4,
    'trio': 3,
    'bootcamp 5': 2,
    'bootcamp 6': 1,
}

const STATUS_NAMES: Record<string, string> = {
    'pending': 'Ожидает',
    'confirmed': 'Подтверждено',
    'cancelled': 'Отменено',
}

export default function AdminHomePage() {
    const [selectedDate, setSelectedDate] = useState<string>(new Date().toISOString().split('T')[0])
    const [selectedRoom, setSelectedRoom] = useState<string>('all')
    const [bookings, setBookings] = useState<Booking[]>([])
    const [loading, setLoading] = useState(false)
    const [showAddModal, setShowAddModal] = useState(false)
    const [formError, setFormError] = useState<string>('')
    const [submitting, setSubmitting] = useState(false)
    
    const [newBooking, setNewBooking] = useState({
        type: 'pc',
        room: 'solo',
        date: new Date().toISOString().split('T')[0],
        time: '12:00',
        name: '',
        game: '',
        contact: '',
        contactMethod: 'telegram',
        status: 'pending'
    })

    useEffect(() => {
        fetchBookings()
    }, [selectedDate, selectedRoom])

    const fetchBookings = async () => {
        setLoading(true)
        try {
            const params = new URLSearchParams({ date: selectedDate })
            if (selectedRoom !== 'all') {
                params.append('room', selectedRoom)
            }

            const res = await fetch(`/api/admin/bookings?${params}`)
            if (res.ok) {
                const data = await res.json()
                setBookings(data.bookings || [])
            }
        } catch (error) {
            console.error('Ошибка при загрузке бронирований:', error)
        } finally {
            setLoading(false)
        }
    }

    const updateStatus = async (id: number, status: string) => {
        try {
            const res = await fetch('/api/admin/bookings', {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id, status }),
            })

            if (res.ok) {
                fetchBookings()
            }
        } catch (error) {
            console.error('Ошибка при обновлении статуса:', error)
        }
    }

    const deleteBooking = async (id: number) => {
        if (!confirm('Вы уверены, что хотите удалить это бронирование?')) return

        try {
            const res = await fetch(`/api/admin/bookings?id=${id}`, {
                method: 'DELETE',
            })

            if (res.ok) {
                fetchBookings()
            }
        } catch (error) {
            console.error('Ошибка при удалении бронирования:', error)
        }
    }

    const handleAddBooking = async (e: React.FormEvent) => {
        e.preventDefault()
        setFormError('')
        setSubmitting(true)

        try {
            const res = await fetch('/api/admin/bookings', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(newBooking),
            })

            const data = await res.json()

            if (res.ok) {
                setShowAddModal(false)
                setNewBooking({
                    type: 'pc',
                    room: 'solo',
                    date: new Date().toISOString().split('T')[0],
                    time: '12:00',
                    name: '',
                    game: '',
                    contact: '',
                    contactMethod: 'telegram',
                    status: 'pending'
                })
                fetchBookings()
            } else {
                setFormError(data.error || 'Ошибка при создании бронирования')
            }
        } catch (error) {
            console.error('Ошибка при создании бронирования:', error)
            setFormError('Ошибка сети. Попробуйте еще раз.')
        } finally {
            setSubmitting(false)
        }
    }

    // Группируем бронирования по комнатам и времени
    const bookingsByRoomAndTime: Record<string, Record<string, Booking[]>> = {}
    bookings.forEach(booking => {
        if (booking.status === 'cancelled') return
        if (!bookingsByRoomAndTime[booking.room]) {
            bookingsByRoomAndTime[booking.room] = {}
        }
        if (!bookingsByRoomAndTime[booking.room][booking.time_slot]) {
            bookingsByRoomAndTime[booking.room][booking.time_slot] = []
        }
        bookingsByRoomAndTime[booking.room][booking.time_slot].push(booking)
    })

    // Генерируем все часы
    const allHours = Array.from({ length: 24 }, (_, i) => {
        return `${i.toString().padStart(2, '0')}:00`
    })

    const rooms = ['solo', 'duo', 'trio', 'bootcamp 5', 'bootcamp 6']

    const formatDate = (dateString: string) => {
        const date = new Date(dateString)
        return date.toLocaleDateString('ru-RU', { 
            weekday: 'long', 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric' 
        })
    }

    return (
        <AdminContainer>
            <AdminHeader/>

            <AdminContent>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '2rem', flexWrap: 'wrap', gap: '1rem' }}>
                    <PageTitle style={{ margin: 0 }}>Управление бронированиями</PageTitle>
                    <AddButton onClick={() => setShowAddModal(true)}>
                        <span>+</span>
                        <span>Добавить бронирование</span>
                    </AddButton>
                </div>

                <FiltersContainer>
                    <FilterGroup>
                        <FilterLabel>Дата</FilterLabel>
                        <FilterInput
                            type="date"
                            value={selectedDate}
                            onChange={(e) => setSelectedDate(e.target.value)}
                        />
                    </FilterGroup>
                    <FilterGroup>
                        <FilterLabel>Тип комнаты</FilterLabel>
                        <FilterSelect
                            value={selectedRoom}
                            onChange={(e) => setSelectedRoom(e.target.value)}
                        >
                            <option value="all">Все комнаты</option>
                            {rooms.map(room => (
                                <option key={room} value={room}>{ROOM_NAMES[room]}</option>
                            ))}
                        </FilterSelect>
                    </FilterGroup>
                </FiltersContainer>

                {loading ? (
                    <LoadingSpinner>
                        <Spinner />
                    </LoadingSpinner>
                ) : (
                    <>
                        {/* Расписание по часам */}
                        {selectedRoom === 'all' ? (
                            rooms.map(room => {
                                const roomBookings = bookingsByRoomAndTime[room] || {}
                                const capacity = ROOM_CAPACITY[room]

                                return (
                                    <RoomCard key={room}>
                                        <RoomCardHeader>
                                            <RoomCardTitle>{ROOM_NAMES[room]}</RoomCardTitle>
                                            <RoomCapacity>{capacity} мест</RoomCapacity>
                                        </RoomCardHeader>
                                        <TimeGrid>
                                            {allHours.map(hour => {
                                                const hourBookings = roomBookings[hour] || []
                                                const booked = hourBookings.length
                                                const isFull = booked >= capacity

                                                return (
                                                    <TimeSlot
                                                        key={hour}
                                                        $available={!isFull}
                                                        $booked={booked}
                                                        $capacity={capacity}
                                                    >
                                                        <TimeSlotHeader>
                                                            <TimeSlotTime>{hour}</TimeSlotTime>
                                                            <TimeSlotCount $full={isFull}>
                                                                {booked}/{capacity}
                                                            </TimeSlotCount>
                                                        </TimeSlotHeader>
                                                        <TimeSlotBookings>
                                                            {hourBookings.length > 0 ? (
                                                                hourBookings.map(booking => (
                                                                    <BookingBadge
                                                                        key={booking.id}
                                                                        $status={booking.status}
                                                                        title={`${booking.name} - ${booking.contact}`}
                                                                    >
                                                                        {booking.name}
                                                                    </BookingBadge>
                                                                ))
                                                            ) : (
                                                                <span style={{ fontSize: '0.75rem', color: 'rgba(109, 103, 148, 0.5)' }}>
                                                                    Свободно
                                                                </span>
                                                            )}
                                                        </TimeSlotBookings>
                                                    </TimeSlot>
                                                )
                                            })}
                                        </TimeGrid>
                                    </RoomCard>
                                )
                            })
                        ) : (
                            (() => {
                                const roomBookings = bookingsByRoomAndTime[selectedRoom] || {}
                                const capacity = ROOM_CAPACITY[selectedRoom]

                                return (
                                    <RoomCard>
                                        <RoomCardHeader>
                                            <RoomCardTitle>{ROOM_NAMES[selectedRoom]}</RoomCardTitle>
                                            <RoomCapacity>{capacity} мест</RoomCapacity>
                                        </RoomCardHeader>
                                        <TimeGrid>
                                            {allHours.map(hour => {
                                                const hourBookings = roomBookings[hour] || []
                                                const booked = hourBookings.length
                                                const isFull = booked >= capacity

                                                return (
                                                    <TimeSlot
                                                        key={hour}
                                                        $available={!isFull}
                                                        $booked={booked}
                                                        $capacity={capacity}
                                                    >
                                                        <TimeSlotHeader>
                                                            <TimeSlotTime>{hour}</TimeSlotTime>
                                                            <TimeSlotCount $full={isFull}>
                                                                {booked}/{capacity}
                                                            </TimeSlotCount>
                                                        </TimeSlotHeader>
                                                        <TimeSlotBookings>
                                                            {hourBookings.length > 0 ? (
                                                                hourBookings.map(booking => (
                                                                    <BookingBadge
                                                                        key={booking.id}
                                                                        $status={booking.status}
                                                                        title={`${booking.name} - ${booking.contact}`}
                                                                    >
                                                                        {booking.name}
                                                                    </BookingBadge>
                                                                ))
                                                            ) : (
                                                                <span style={{ fontSize: '0.75rem', color: 'rgba(109, 103, 148, 0.5)' }}>
                                                                    Свободно
                                                                </span>
                                                            )}
                                                        </TimeSlotBookings>
                                                    </TimeSlot>
                                                )
                                            })}
                                        </TimeGrid>
                                    </RoomCard>
                                )
                            })()
                        )}

                        {/* Список всех бронирований */}
                        <SectionTitle>
                            Все бронирования на {formatDate(selectedDate)}
                        </SectionTitle>

                        {bookings.length === 0 ? (
                            <EmptyState>
                                <EmptyStateIcon>📅</EmptyStateIcon>
                                <EmptyStateText>Нет бронирований на эту дату</EmptyStateText>
                            </EmptyState>
                        ) : (
                            <BookingsList>
                                {bookings.map(booking => (
                                    <BookingCard key={booking.id} $status={booking.status}>
                                        <BookingCardHeader>
                                            <BookingCardInfo>
                                                <BookingCardTitle>{booking.name}</BookingCardTitle>
                                                <BookingCardMeta>
                                                    <span>🕐 {booking.time_slot}</span>
                                                    <span>🖥 {ROOM_NAMES[booking.room] || booking.room}</span>
                                                    {booking.game && <span>🎮 {booking.game}</span>}
                                                    <span>📞 {booking.contact}</span>
                                                    {booking.contact_method && (
                                                        <span>💬 {booking.contact_method}</span>
                                                    )}
                                                </BookingCardMeta>
                                            </BookingCardInfo>
                                            <BookingCardActions>
                                                <StatusSelect
                                                    $status={booking.status}
                                                    value={booking.status}
                                                    onChange={(e) => updateStatus(booking.id, e.target.value)}
                                                >
                                                    <option value="pending">Ожидает</option>
                                                    <option value="confirmed">Подтверждено</option>
                                                    <option value="cancelled">Отменено</option>
                                                </StatusSelect>
                                                <DeleteButton onClick={() => deleteBooking(booking.id)}>
                                                    Удалить
                                                </DeleteButton>
                                            </BookingCardActions>
                                        </BookingCardHeader>
                                    </BookingCard>
                                ))}
                            </BookingsList>
                        )}
                    </>
                )}

                {/* Модальное окно для добавления бронирования */}
                {showAddModal && (
                    <ModalOverlay onClick={() => !submitting && setShowAddModal(false)}>
                        <ModalContent onClick={(e) => e.stopPropagation()} onSubmit={handleAddBooking}>
                            <ModalHeader>
                                <ModalTitle>Добавить бронирование</ModalTitle>
                                <ModalCloseButton 
                                    type="button" 
                                    onClick={() => !submitting && setShowAddModal(false)}
                                >
                                    ×
                                </ModalCloseButton>
                            </ModalHeader>
                            <ModalBody>
                                <FormRow>
                                    <div>
                                        <FormLabel>Тип активности</FormLabel>
                                        <StyledFormSelect
                                            value={newBooking.type}
                                            onChange={(e) => setNewBooking({ ...newBooking, type: e.target.value })}
                                            required
                                        >
                                            <option value="pc">Играть на ПК</option>
                                            <option value="ps">Играть на PS</option>
                                            <option value="tv">Смотреть трансляции</option>
                                            <option value="zayvka">Заявка</option>
                                        </StyledFormSelect>
                                    </div>
                                    <div>
                                        <FormLabel>Тип комнаты</FormLabel>
                                        <StyledFormSelect
                                            value={newBooking.room}
                                            onChange={(e) => setNewBooking({ ...newBooking, room: e.target.value })}
                                            required
                                        >
                                            <option value="solo">Solo (5 мест)</option>
                                            <option value="duo">Duo (4 места)</option>
                                            <option value="trio">Trio (3 места)</option>
                                            <option value="bootcamp 5">Bootcamp 5 (2 места)</option>
                                            <option value="bootcamp 6">Bootcamp 6 (1 место)</option>
                                        </StyledFormSelect>
                                    </div>
                                </FormRow>

                                <FormRow>
                                    <div>
                                        <FormLabel>Дата</FormLabel>
                                        <StyledFormInput
                                            type="date"
                                            value={newBooking.date}
                                            onChange={(e) => setNewBooking({ ...newBooking, date: e.target.value })}
                                            min={new Date().toISOString().split('T')[0]}
                                            required
                                        />
                                    </div>
                                    <div>
                                        <FormLabel>Время</FormLabel>
                                        <StyledFormSelect
                                            value={newBooking.time}
                                            onChange={(e) => setNewBooking({ ...newBooking, time: e.target.value })}
                                            required
                                        >
                                            {Array.from({ length: 24 }, (_, i) => {
                                                const hour = i.toString().padStart(2, '0')
                                                return (
                                                    <option key={hour} value={`${hour}:00`}>
                                                        {hour}:00
                                                    </option>
                                                )
                                            })}
                                        </StyledFormSelect>
                                    </div>
                                </FormRow>

                                <div>
                                    <FormLabel>Имя клиента</FormLabel>
                                    <StyledFormInput
                                        type="text"
                                        value={newBooking.name}
                                        onChange={(e) => setNewBooking({ ...newBooking, name: e.target.value })}
                                        placeholder="Введите имя"
                                        required
                                    />
                                </div>

                                <div>
                                    <FormLabel>Игра (необязательно)</FormLabel>
                                    <StyledFormInput
                                        type="text"
                                        value={newBooking.game}
                                        onChange={(e) => setNewBooking({ ...newBooking, game: e.target.value })}
                                        placeholder="Название игры"
                                    />
                                </div>

                                <div>
                                    <FormLabel>Контактный номер</FormLabel>
                                    <StyledFormInput
                                        type="text"
                                        value={newBooking.contact}
                                        onChange={(e) => setNewBooking({ ...newBooking, contact: e.target.value })}
                                        placeholder="+7 (777) 123-45-67"
                                        required
                                    />
                                </div>

                                <FormRow>
                                    <div>
                                        <FormLabel>Способ связи</FormLabel>
                                        <StyledFormSelect
                                            value={newBooking.contactMethod}
                                            onChange={(e) => setNewBooking({ ...newBooking, contactMethod: e.target.value })}
                                        >
                                            <option value="telegram">Telegram</option>
                                            <option value="whatsapp">WhatsApp</option>
                                            <option value="phone">Телефон</option>
                                        </StyledFormSelect>
                                    </div>
                                    <div>
                                        <FormLabel>Статус</FormLabel>
                                        <StyledFormSelect
                                            value={newBooking.status}
                                            onChange={(e) => setNewBooking({ ...newBooking, status: e.target.value })}
                                        >
                                            <option value="pending">Ожидает</option>
                                            <option value="confirmed">Подтверждено</option>
                                            <option value="cancelled">Отменено</option>
                                        </StyledFormSelect>
                                    </div>
                                </FormRow>

                                {formError && <ErrorMessage>{formError}</ErrorMessage>}
                            </ModalBody>
                            <ModalFooter>
                                <CancelButton 
                                    type="button" 
                                    onClick={() => setShowAddModal(false)}
                                    disabled={submitting}
                                >
                                    Отмена
                                </CancelButton>
                                <SubmitButton type="submit" disabled={submitting}>
                                    {submitting ? 'Создание...' : 'Создать бронирование'}
                                </SubmitButton>
                            </ModalFooter>
                        </ModalContent>
                    </ModalOverlay>
                )}
            </AdminContent>
        </AdminContainer>
    )
}
