'use client'

import { useEffect, useState, FormEvent } from 'react'
import AdminHeader from '@/components/AdminHeader'
import {
    AdminContainer,
    AdminContent,
    PageTitle,
    LoadingSpinner,
    Spinner,
    RoomCard,
    RoomCardHeader,
    RoomCardTitle,
    FilterInput,
    DeleteButton
} from "@/styles/admin.styled"
import styled from 'styled-components'
import { whiteColor, modalColor, lightGreenColor, blackColor } from '@/styles/colors'

const ContactCard = styled.div`
    background: rgba(15, 15, 23, 0.6);
    border: 1px solid rgba(109, 103, 148, 0.2);
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 1rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: all 0.2s;
    
    &:hover {
        border-color: rgba(76, 230, 94, 0.3);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
    }
`

const ContactInfo = styled.div`
    flex: 1;
`

const ContactType = styled.div`
    font-size: 0.875rem;
    color: ${modalColor};
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 0.5rem;
`

const ContactValue = styled.div`
    font-size: 1.125rem;
    color: ${whiteColor};
    word-break: break-word;
`

const EditButton = styled.button`
    background: rgba(76, 230, 94, 0.2);
    border: 1px solid rgba(76, 230, 94, 0.4);
    color: ${lightGreenColor};
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    margin-left: 1rem;
    
    &:hover {
        background: rgba(76, 230, 94, 0.3);
        border-color: ${lightGreenColor};
        transform: translateY(-1px);
    }
`

const ModalOverlay = styled.div`
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.8);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    padding: 1rem;
`

const ModalContent = styled.form`
    background: rgba(15, 15, 23, 0.95);
    border: 1px solid rgba(109, 103, 148, 0.3);
    border-radius: 16px;
    padding: 2rem;
    max-width: 500px;
    width: 100%;
`

const ModalHeader = styled.div`
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
`

const ModalTitle = styled.h3`
    font-size: 1.5rem;
    color: ${whiteColor};
    margin: 0;
`

const CloseButton = styled.button`
    background: transparent;
    border: none;
    color: ${modalColor};
    font-size: 1.5rem;
    cursor: pointer;
    padding: 0;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    transition: all 0.2s;
    
    &:hover {
        background: rgba(109, 103, 148, 0.2);
        color: ${whiteColor};
    }
`

const ModalBody = styled.div`
    margin-bottom: 1.5rem;
`

const FormLabel = styled.label`
    display: block;
    font-size: 0.875rem;
    color: ${modalColor};
    margin-bottom: 0.5rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
`

const FormInput = styled(FilterInput)`
    width: 100%;
`

const ModalFooter = styled.div`
    display: flex;
    gap: 1rem;
    justify-content: flex-end;
`

const CancelButton = styled.button`
    background: rgba(109, 103, 148, 0.2);
    border: 1px solid rgba(109, 103, 148, 0.4);
    color: ${modalColor};
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover {
        background: rgba(109, 103, 148, 0.3);
        border-color: ${modalColor};
    }
`

const SaveButton = styled.button`
    background: rgba(76, 230, 94, 0.2);
    border: 1px solid rgba(76, 230, 94, 0.4);
    color: ${lightGreenColor};
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover {
        background: rgba(76, 230, 94, 0.3);
        border-color: ${lightGreenColor};
    }
`

interface Contact {
    id: number
    type: string
    value: string
}

export default function AdminContactsPage() {
    const [contacts, setContacts] = useState<Contact[]>([])
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState('')
    const [editRow, setEditRow] = useState<Contact | null>(null)
    const [showModal, setShowModal] = useState(false)

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

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

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

    const handleSave = async (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        const form = e.currentTarget
        const formData = new FormData(form)
        const updatedValue = formData.get('value') as string

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

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

    return (
        <AdminContainer>
            <AdminHeader />
            <AdminContent>
                <PageTitle>Контакты</PageTitle>

                {loading ? (
                    <LoadingSpinner>
                        <Spinner />
                    </LoadingSpinner>
                ) : error ? (
                    <div style={{ color: '#dc3545', padding: '2rem' }}>{error}</div>
                ) : (
                    <div>
                        {contacts.map((row) => (
                            <ContactCard key={row.id}>
                                <ContactInfo>
                                    <ContactType>{row.type}</ContactType>
                                    <ContactValue>{row.value}</ContactValue>
                                </ContactInfo>
                                <EditButton onClick={() => handleEditClick(row)}>
                                    Редактировать
                                </EditButton>
                            </ContactCard>
                        ))}
                    </div>
                )}

                {showModal && editRow && (
                    <ModalOverlay onClick={() => setShowModal(false)}>
                        <ModalContent onClick={(e) => e.stopPropagation()} onSubmit={handleSave}>
                            <ModalHeader>
                                <ModalTitle>Редактировать контакт</ModalTitle>
                                <CloseButton type="button" onClick={() => setShowModal(false)}>
                                    ×
                                </CloseButton>
                            </ModalHeader>
                            <ModalBody>
                                <FormLabel>Тип: {editRow.type}</FormLabel>
                                <FormLabel style={{ marginTop: '1rem' }}>Значение</FormLabel>
                                <FormInput
                                    name="value"
                                    type="text"
                                    defaultValue={editRow.value}
                                    required
                                />
                            </ModalBody>
                            <ModalFooter>
                                <CancelButton type="button" onClick={() => setShowModal(false)}>
                                    Отмена
                                </CancelButton>
                                <SaveButton type="submit">
                                    Сохранить
                                </SaveButton>
                            </ModalFooter>
                        </ModalContent>
                    </ModalOverlay>
                )}
            </AdminContent>
        </AdminContainer>
    )
}
