import React, { FC, useState, useMemo } from 'react';
import { Button, Space, Spin, Table, Card, Typography } from 'antd';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import { Link, useNavigate, useParams } from 'react-router';
import { useApolloClient } from '@apollo/client';
import { gql } from '@apollo/client';

import { extractParamName, extractParamValue } from '../../../../basic/Utils';
import ErrorModal from '../../../basic/ErrorModal';
import { useSearchDoctorAppointmentQuery } from '../../../../__generate/graphql-frontend'

const { Title, Text } = Typography;

// Расширенный запрос для получения данных о записях с информацией о врачах и пациентах
const SEARCH_DOCTOR_APPOINTMENT_WITH_DETAILS = gql`
  query searchDoctorAppointmentWithDetails($cond: String) {
    searchDoctorAppointment(cond: $cond) {
      elems {
        id
        beginDate
        endDate
        descr
        doctorSchedule {
          id
          clinicDoctor {
            entity {
              doctor {
                entity {
                  person {
                    entity {
                      firstName
                      lastName
                    }
                  }
                  doctorType {
                    name
                  }
                }
              }
            }
          }
        }
        clinicCustomer {
          entity {
            customer {
              entity {
                person {
                  entity {
                    firstName
                    lastName
                  }
                }
              }
            }
          }
        }
      }
    }
  }
`;

export const DoctorAppointmentList: FC<{ selectedDoctorAppointment?: string | null, setSelectedDoctorAppointment?: (value: string) => void }> = ({ selectedDoctorAppointment, setSelectedDoctorAppointment }) => {

    const client = useApolloClient()
    const navigate = useNavigate();
    const { filterStr } = useParams()
    const [error, setError] = useState<Error | null>(null)
    
    // Функция для получения понедельника текущей недели
    const getMondayOfWeek = (date: Date) => {
        const d = new Date(date);
        const day = d.getDay(); // 0 = воскресенье, 1 = понедельник, ... 6 = суббота
        // Вычисляем количество дней до понедельника
        // Для воскресенья (0) нужно вернуться на 6 дней назад к понедельнику
        // Для остальных дней: понедельник на (day - 1) дней назад
        const daysFromMonday = day === 0 ? 6 : day - 1;
        d.setDate(d.getDate() - daysFromMonday);
        d.setHours(0, 0, 0, 0);
        return d;
    };

    // Состояние для навигации по неделям - всегда начинаем с понедельника
    const [currentStartDate, setCurrentStartDate] = useState(() => {
        const today = new Date();
        const monday = getMondayOfWeek(today);
        console.log('Initializing currentStartDate:', {
            today: today,
            todayDayOfWeek: today.getDay(),
            monday: monday,
            mondayDayOfWeek: monday.getDay()
        });
        return monday;
    });
    
    const DAYS_TO_SHOW = 7; // Показываем 7 дней (полная неделя)

    const { data, loading, error: queryError } = useSearchDoctorAppointmentQuery(
        {
            variables: {
                cond: (filterStr && filterStr !== 'undefined' && selectedDoctorAppointment !== null ) ? `it.${extractParamName(filterStr)}.id=='${extractParamValue(filterStr)}'` : null
            }
        })

    const elemList = data?.searchDoctorAppointment.elems

    // Функция для получения диапазона дат для отображения
    const getDisplayDates = (startDate: Date, daysCount: number) => {
        const dates = [];
        for (let i = 0; i < daysCount; i++) {
            const date = new Date(startDate);
            date.setDate(startDate.getDate() + i);
            dates.push(date.toISOString().split('T')[0]);
        }
        return dates;
    };

    // Функция для получения уникальных врачей
    const getUniqueDoctors = (appointments: typeof elemList) => {
        if (!appointments) return [];
        
        const doctors = new Map<string, string>();
        appointments.forEach(appointment => {
            const doctorId = appointment.doctorSchedule?.id;
            if (doctorId) {
                doctors.set(doctorId, `Врач ID: ${doctorId}`);
            }
        });
        
        return Array.from(doctors.entries()).map(([id, name]) => ({ id, name }));
    };

    // Функция для получения записей врача на определенную дату
    const getDoctorAppointmentsForDate = (appointments: typeof elemList, doctorId: string, date: string) => {
        if (!appointments) return [];
        
        return appointments.filter(appointment => {
            const appointmentDate = new Date(appointment.beginDate).toISOString().split('T')[0];
            return appointment.doctorSchedule?.id === doctorId && appointmentDate === date;
        });
    };

    // Функция для форматирования даты для заголовка колонки
    const formatDateHeader = (dateStr: string) => {
        const date = new Date(dateStr);
        const today = new Date();
        const isToday = date.toDateString() === today.toDateString();
        
        // Определяем дни недели в правильном порядке (понедельник - первый)
        const weekdayNames = ['пн', 'вт', 'ср', 'чт', 'пт', 'сб', 'вс'];
        const dayOfWeek = date.getDay(); // 0 = воскресенье, 1 = понедельник, и т.д.
        const weekdayName = weekdayNames[dayOfWeek];
        
        return (
            <div style={{ textAlign: 'center' }}>
                <div style={{ fontWeight: isToday ? 'bold' : 'normal', color: isToday ? '#1890ff' : 'inherit' }}>
                    {weekdayName}
                </div>
                <div style={{ fontSize: '12px', color: isToday ? '#1890ff' : '#666' }}>
                    {date.toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' })}
                </div>
            </div>
        );
    };

    // Функция для форматирования времени
    const formatTime = (dateTimeStr: string) => {
        const date = new Date(dateTimeStr);
        return date.toLocaleTimeString('ru-RU', {
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    // Функция для получения цвета карточки на основе времени
    const getAppointmentColor = (beginDate: string) => {
        const hour = new Date(beginDate).getHours();
        
        if (hour < 10) {
            return { bg: '#e6f7ff', border: '#40a9ff' }; // Утро - голубой
        } else if (hour < 14) {
            return { bg: '#f6ffed', border: '#73d13d' }; // День - зеленый
        } else if (hour < 18) {
            return { bg: '#fff7e6', border: '#ffa940' }; // После обеда - оранжевый
        } else {
            return { bg: '#f9f0ff', border: '#b37feb' }; // Вечер - фиолетовый
        }
    };

    // Навигация по неделям
    const navigateWeek = (direction: 'prev' | 'next') => {
        const newDate = new Date(currentStartDate);
        newDate.setDate(currentStartDate.getDate() + (direction === 'next' ? 7 : -7));
        setCurrentStartDate(newDate);
    };

    const goToToday = () => {
        const today = new Date();
        setCurrentStartDate(getMondayOfWeek(today));
    };

    const displayDates = useMemo(() => {
        // Отладочная информация для проверки дней недели
        console.log('currentStartDate:', currentStartDate, 'day of week:', currentStartDate.getDay());
        const dates = getDisplayDates(currentStartDate, DAYS_TO_SHOW);
        console.log('displayDates:', dates.map(date => {
            const d = new Date(date);
            return `${date} (${d.getDay()})`;
        }));
        return dates;
    }, [currentStartDate]);
    const uniqueDoctors = useMemo(() => getUniqueDoctors(elemList), [elemList]);



    // Функция для форматирования периода
    const formatPeriod = () => {
        const endDate = new Date(currentStartDate.getTime() + (DAYS_TO_SHOW - 1) * 24 * 60 * 60 * 1000);
        const startStr = currentStartDate.toLocaleDateString('ru-RU', { 
            day: '2-digit', 
            month: 'long',
            year: 'numeric'
        });
        const endStr = endDate.toLocaleDateString('ru-RU', { 
            day: '2-digit', 
            month: 'long',
            year: 'numeric'
        });
        return `${startStr} - ${endStr}`;
    };

    // Создание колонок для таблицы
    const columns = [
        {
            title: 'Врач',
            dataIndex: 'doctorName',
            key: 'doctorName',
            width: 200,
            fixed: 'left' as const,
            render: (text: string) => <Text strong style={{ fontSize: '14px' }}>{text}</Text>
        },
        ...displayDates.map(date => {
            // Все колонки одинаковой ширины
            const columnWidth = 120;
            
            return {
                title: formatDateHeader(date),
                dataIndex: date,
                key: date,
                width: columnWidth,
                render: (appointments: any[]) => (
                    <div style={{ minHeight: '80px', padding: '4px' }}>
                        {appointments && appointments.length > 0 ? (
                            <Space direction="vertical" size="small" style={{ width: '100%' }}>
                                {appointments.map(appointment => {
                                    const colors = getAppointmentColor(appointment.beginDate);
                                    const isSelected = selectedDoctorAppointment === appointment.id;
                                    
                                    return (
                                        <Card
                                            key={appointment.id}
                                            size="small"
                                            hoverable
                                            onClick={() => { if (setSelectedDoctorAppointment) setSelectedDoctorAppointment(appointment.id) }}
                                            style={{
                                                cursor: setSelectedDoctorAppointment ? 'pointer' : 'default',
                                                backgroundColor: isSelected ? '#1890ff' : colors.bg,
                                                border: `2px solid ${isSelected ? '#ffffff' : colors.border}`,
                                                borderRadius: '8px',
                                                boxShadow: isSelected ? '0 4px 12px rgba(24, 144, 255, 0.3)' : '0 2px 8px rgba(0, 0, 0, 0.1)',
                                                transform: isSelected ? 'scale(1.02)' : 'scale(1)',
                                                transition: 'all 0.2s ease-in-out'
                                            }}
                                            bodyStyle={{ padding: '8px' }}
                                        >
                                            <div style={{ 
                                                fontSize: '12px', 
                                                color: isSelected ? '#ffffff' : '#000',
                                                fontWeight: '500'
                                            }}>
                                                <div style={{ 
                                                    fontWeight: 'bold', 
                                                    marginBottom: '4px',
                                                    color: isSelected ? '#ffffff' : colors.border
                                                }}>
                                                    {formatTime(appointment.beginDate)} - {formatTime(appointment.endDate)}
                                                </div>
                                                <div style={{ 
                                                    marginBottom: '2px',
                                                    color: isSelected ? '#ffffff' : '#666'
                                                }}>
                                                    👤 Пациент ID: {appointment.clinicCustomer?.entityId || 'Не указан'}
                                                </div>
                                                {appointment.descr && (
                                                    <div style={{ 
                                                        fontSize: '11px',
                                                        color: isSelected ? '#ffffff' : '#999',
                                                        fontStyle: 'italic',
                                                        marginBottom: '4px'
                                                    }}>
                                                        {appointment.descr}
                                                    </div>
                                                )}
                                                {selectedDoctorAppointment !== null && (
                                                    <div style={{ marginTop: '6px', borderTop: `1px solid ${isSelected ? '#ffffff' : '#eee'}`, paddingTop: '4px' }}>
                                                        <Link 
                                                            to={`/ClinicScheduleAgg/DoctorAppointment/Update/${appointment.id}`} 
                                                            style={{ 
                                                                fontSize: '11px', 
                                                                marginRight: '12px',
                                                                color: isSelected ? '#ffffff' : colors.border,
                                                                fontWeight: 'bold'
                                                            }}
                                                        >
                                                            ✏️ Изменить
                                                        </Link>
                                                        <Link 
                                                            to={`/ClinicScheduleAgg/DoctorAppointment/Delete/${appointment.id}`} 
                                                            style={{ 
                                                                fontSize: '11px',
                                                                color: isSelected ? '#ffffff' : '#ff4d4f',
                                                                fontWeight: 'bold'
                                                            }}
                                                        >
                                                            🗑️ Удалить
                                                        </Link>
                                                    </div>
                                                )}
                                            </div>
                                        </Card>
                                    );
                                })}
                            </Space>
                        ) : (
                            <div style={{ 
                                color: '#bfbfbf', 
                                fontSize: '12px', 
                                textAlign: 'center', 
                                paddingTop: '30px',
                                fontStyle: 'italic'
                            }}>
                                Нет записей
                            </div>
                        )}
                    </div>
                )
            };
        })
    ];

    // Создание данных для таблицы
    const tableData = uniqueDoctors.map(doctor => {
        const row: any = {
            key: doctor.id,
            doctorName: doctor.name
        };
        
        displayDates.forEach(date => {
            row[date] = getDoctorAppointmentsForDate(elemList, doctor.id, date);
        });
        
        return row;
    });

    if (loading) return (<Spin tip="Загрузка..." />);
    if (queryError) {
        return (<ErrorModal error={queryError} setError={setError} />)
    } else {
    
        client.refetchQueries({include:["searchDoctorAppointment"]})
        return (
            <Space direction='vertical' style={{ width: '100%' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Title level={4}>Расписание приема врачей</Title>
                    {selectedDoctorAppointment === undefined && (
                        <Button
                            type="primary"
                            onClick={() => {
                                navigate(`/ClinicScheduleAgg/DoctorAppointment/Create/${filterStr}`)
                            }}
                        >
                            Создать запись
                        </Button>
                    )}
                </div>

                {/* Навигация по дням */}
                <div style={{ 
                    display: 'flex', 
                    justifyContent: 'center', 
                    alignItems: 'center', 
                    gap: '16px',
                    padding: '16px',
                    backgroundColor: '#fafafa',
                    borderRadius: '8px',
                    border: '1px solid #d9d9d9'
                }}>
                    <Button 
                        icon={<LeftOutlined />} 
                        onClick={() => navigateWeek('prev')}
                        type="text"
                        size="large"
                    >
                        Предыдущая неделя
                    </Button>
                    
                    <Button 
                        onClick={goToToday}
                        type="primary"
                        ghost
                    >
                        Сегодня
                    </Button>
                    
                    <Text strong style={{ fontSize: '16px', minWidth: '200px', textAlign: 'center' }}>
                        {formatPeriod()}
                    </Text>
                    
                    <Button 
                        onClick={() => navigateWeek('next')}
                        type="text"
                        size="large"
                    >
                        Следующая неделя <RightOutlined />
                    </Button>
                </div>
        
                {elemList && elemList.length > 0 ? (
                    <Table
                        columns={columns}
                        dataSource={tableData}
                        pagination={false}
                        scroll={{ x: 'max-content' }}
                        bordered
                        size="small"
                        style={{ 
                            backgroundColor: '#ffffff',
                            borderRadius: '8px',
                            overflow: 'hidden'
                        }}
                    />
                ) : (
                    <Card>
                        <div style={{ textAlign: 'center', padding: '40px' }}>
                            <Text type="secondary">Записи не найдены</Text>
                        </div>
                    </Card>
                )}
            </Space>
        )
    }
}
