import React from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { Card, Descriptions, Spin, Button, Tag } from 'antd';
import { useCalendar } from '../../hooks/useCalendars';
import dayjs from 'dayjs';

const CalendarDetailPage: React.FC = () => {
    const { id } = useParams<{ id: string }>();
    const navigate = useNavigate();
    const { data: calendar, isLoading } = useCalendar(id || '');

    const isBadValue = (val: unknown) =>
        val === '-' || val === 'undefined' || val === '' || val === null || val === undefined;

    const displayValue = (val: unknown) => (isBadValue(val) ? '-' : String(val));

    const formatDate = (dateStr: string) => {
        if (isBadValue(dateStr)) return '-';
        const d = dayjs(dateStr);
        return d.isValid() ? d.format('DD.MM.YYYY HH:mm') : dateStr;
    };

    if (isLoading) return <Spin size="large" style={{ display: 'block', margin: '100px auto' }} />;
    if (!calendar) return <p>Календарь не найден</p>;

    const tagsStr = Array.isArray(calendar.tags) && calendar.tags.length > 0 ? calendar.tags.join(', ') : '-';

    return (
        <Card title={`Календарь ${calendar.title || calendar.id}`}>
            <Descriptions bordered column={1}>
                <Descriptions.Item label="ID">{calendar.id}</Descriptions.Item>
                <Descriptions.Item label="Название">{calendar.title}</Descriptions.Item>
                <Descriptions.Item label="Короткое имя">{displayValue(calendar.short_name)}</Descriptions.Item>
                <Descriptions.Item label="Описание">{displayValue(calendar.description)}</Descriptions.Item>
                <Descriptions.Item label="Тип">
                    <Tag color={calendar.type === 'commercial' ? 'gold' : 'blue'}>{calendar.type}</Tag>
                </Descriptions.Item>
                <Descriptions.Item label="Статус">
                    <Tag color={calendar.status === 'active' ? 'green' : calendar.status === 'frozen' ? 'orange' : 'red'}>
                        {calendar.status}
                    </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="Причина">{displayValue(calendar.reason)}</Descriptions.Item>
                <Descriptions.Item label="Категория">{displayValue(calendar.category)}</Descriptions.Item>
                <Descriptions.Item label="Владелец">
                    {!isBadValue(calendar.owner_id) ? (
                        <Link to={`/users/${calendar.owner_id}`}>{calendar.owner_id}</Link>
                    ) : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="Цвет">{displayValue(calendar.color)}</Descriptions.Item>
                <Descriptions.Item label="Изображение">{displayValue(calendar.image_url)}</Descriptions.Item>
                <Descriptions.Item label="Подтверждение">{displayValue(calendar.confirmation)}</Descriptions.Item>
                <Descriptions.Item label="Теги">{tagsStr}</Descriptions.Item>
                <Descriptions.Item label="Рейтинг">{calendar.rating_avg} ({calendar.rating_count})</Descriptions.Item>
                <Descriptions.Item label="Настройки">
                    {calendar.settings ? JSON.stringify(calendar.settings) : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="Создано">{formatDate(calendar.created_at)}</Descriptions.Item>
                <Descriptions.Item label="Обновлено">{formatDate(calendar.updated_at)}</Descriptions.Item>
            </Descriptions>
            <Button style={{ marginTop: 16 }} onClick={() => navigate('/calendars')}>Назад к списку</Button>
        </Card>
    );
};

export default CalendarDetailPage;
