import { useState } from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useCalendar } from './useCalendar';
import { useIsMobile } from '../../hooks/useIsMobile';

const MONTH_NAMES = [
  'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
  'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь',
];

const DAY_HEADERS = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];

const STATUS_COLORS = {
  'новая':        '#8C9097',
  'замер':        '#F59E0B',
  'согласование': '#8b5cf6',
  'монтаж':       '#4361EE',
  'закрыт':       '#22C55E',
};

function getStatusColor(status) {
  return STATUS_COLORS[status] || '#8C9097';
}

// Returns a 6×7 array of Date objects for the calendar grid (Mon-first)
function buildCalendarDays(year, month) {
  const firstDay = new Date(year, month, 1);
  // getDay(): 0=Sun,1=Mon,...,6=Sat — convert to Mon=0,...,Sun=6
  const startOffset = (firstDay.getDay() + 6) % 7;
  const days = [];
  for (let i = 0; i < 42; i++) {
    const d = new Date(year, month, 1 - startOffset + i);
    days.push(d);
  }
  return days;
}

function isSameDay(a, b) {
  return a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate() === b.getDate();
}

function OrderChip({ order }) {
  const color = getStatusColor(order.status);
  return (
    <div
      title={`${order.name} — ${order.status}`}
      style={{
        background: color + '1A',
        color,
        fontSize: '0.68rem',
        fontWeight: 600,
        padding: '2px 6px',
        borderRadius: '4px',
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        maxWidth: '100%',
        lineHeight: 1.4,
      }}
    >
      {order.name}
    </div>
  );
}

function DayCell({ date, orders, isCurrentMonth, isToday, isSelected, onSelect, isMobile }) {
  const dayOrders = orders.filter((o) => o.scheduled_at && isSameDay(new Date(o.scheduled_at), date));
  const visible = dayOrders.slice(0, 2);
  const extra = dayOrders.length - visible.length;

  return (
    <div
      onClick={() => onSelect(date)}
      style={{
        minHeight: isMobile ? '60px' : '80px',
        padding: isMobile ? '4px' : '6px 8px',
        border: isSelected ? '2px solid #4361EE' : '1px solid #E9ECEF',
        borderRadius: '8px',
        background: isToday ? '#EEF2FF' : '#FFFFFF',
        cursor: 'pointer',
        display: 'flex',
        flexDirection: 'column',
        gap: '3px',
        transition: 'border-color 0.15s, background 0.15s',
        overflow: 'hidden',
      }}
      onMouseEnter={(e) => {
        if (!isSelected) e.currentTarget.style.borderColor = '#A5B4FC';
      }}
      onMouseLeave={(e) => {
        if (!isSelected) e.currentTarget.style.borderColor = '#E9ECEF';
      }}
    >
      <span
        style={{
          fontSize: isMobile ? '0.72rem' : '0.8rem',
          fontWeight: isToday ? 700 : 500,
          color: isToday
            ? '#4361EE'
            : isCurrentMonth
              ? 'var(--text-main, #1E1E2D)'
              : 'var(--text-muted, #8C9097)',
          lineHeight: 1,
          flexShrink: 0,
        }}
      >
        {date.getDate()}
      </span>

      {!isMobile && visible.map((o) => (
        <OrderChip key={o.id} order={o} />
      ))}

      {isMobile && dayOrders.length > 0 && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px' }}>
          {dayOrders.map((o) => (
            <div
              key={o.id}
              style={{
                width: '8px', height: '8px', borderRadius: '50%',
                background: getStatusColor(o.status),
                flexShrink: 0,
              }}
            />
          ))}
        </div>
      )}

      {!isMobile && extra > 0 && (
        <span style={{ fontSize: '0.65rem', color: '#8C9097', fontWeight: 600 }}>
          +{extra} ещё
        </span>
      )}
    </div>
  );
}

function DayDetail({ date, orders }) {
  const dayOrders = orders.filter((o) => o.scheduled_at && isSameDay(new Date(o.scheduled_at), date));

  if (dayOrders.length === 0) {
    return (
      <div style={{ color: 'var(--text-muted, #8C9097)', fontSize: '0.85rem' }}>
        На этот день записей нет
      </div>
    );
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
      {dayOrders.map((o) => {
        const color = getStatusColor(o.status);
        const time = new Date(o.scheduled_at).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
        return (
          <div
            key={o.id}
            className="glass-panel"
            style={{
              padding: '12px 16px',
              borderLeft: `3px solid ${color}`,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              gap: '12px',
            }}
          >
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: '0.92rem', marginBottom: '2px' }}>
                {o.name}
              </div>
              <div style={{ fontSize: '0.78rem', color: 'var(--text-muted, #8C9097)' }}>
                {o.phone}{o.area_sqm ? ` · ${o.area_sqm} м²` : ''}{o.film_thickness ? ` · ${o.film_thickness} мкм` : ''}
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: '4px', flexShrink: 0 }}>
              <span
                style={{
                  background: color + '1A',
                  color,
                  fontSize: '0.72rem',
                  fontWeight: 700,
                  padding: '2px 8px',
                  borderRadius: '12px',
                  textTransform: 'uppercase',
                  letterSpacing: '0.3px',
                }}
              >
                {o.status}
              </span>
              <span style={{ fontSize: '0.75rem', color: 'var(--text-muted, #8C9097)' }}>{time}</span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

const CalendarPage = () => {
  const today = new Date();
  const [year, setYear] = useState(today.getFullYear());
  const [month, setMonth] = useState(today.getMonth());
  const [selectedDate, setSelectedDate] = useState(today);
  const isMobile = useIsMobile();
  const { orders, loading } = useCalendar(year, month);

  const prevMonth = () => {
    if (month === 0) { setYear((y) => y - 1); setMonth(11); }
    else setMonth((m) => m - 1);
  };

  const nextMonth = () => {
    if (month === 11) { setYear((y) => y + 1); setMonth(0); }
    else setMonth((m) => m + 1);
  };

  const calendarDays = buildCalendarDays(year, month);

  const selectedDateLabel = selectedDate.toLocaleDateString('ru-RU', {
    weekday: 'long', day: 'numeric', month: 'long',
  });

  return (
    <div style={{ padding: isMobile ? '16px' : '30px', maxWidth: '1100px' }}>
      <h1 style={{
        fontFamily: 'var(--font-heading)', fontSize: '1.5rem', fontWeight: 800,
        marginBottom: '24px',
      }}>
        Календарь
      </h1>

      {/* Month navigation header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: '16px',
      }}>
        <button
          onClick={prevMonth}
          aria-label="Предыдущий месяц"
          style={{
            background: 'none', border: '1.5px solid #E9ECEF',
            borderRadius: '8px', cursor: 'pointer', padding: '6px 10px',
            display: 'flex', alignItems: 'center', color: '#1E1E2D',
            transition: 'border-color 0.15s',
          }}
          onMouseEnter={(e) => e.currentTarget.style.borderColor = '#4361EE'}
          onMouseLeave={(e) => e.currentTarget.style.borderColor = '#E9ECEF'}
        >
          <ChevronLeft size={18} />
        </button>

        <h2 style={{
          fontFamily: 'var(--font-heading)', fontWeight: 700,
          fontSize: isMobile ? '1rem' : '1.15rem',
          color: '#1E1E2D',
        }}>
          {MONTH_NAMES[month]} {year}
        </h2>

        <button
          onClick={nextMonth}
          aria-label="Следующий месяц"
          style={{
            background: 'none', border: '1.5px solid #E9ECEF',
            borderRadius: '8px', cursor: 'pointer', padding: '6px 10px',
            display: 'flex', alignItems: 'center', color: '#1E1E2D',
            transition: 'border-color 0.15s',
          }}
          onMouseEnter={(e) => e.currentTarget.style.borderColor = '#4361EE'}
          onMouseLeave={(e) => e.currentTarget.style.borderColor = '#E9ECEF'}
        >
          <ChevronRight size={18} />
        </button>
      </div>

      {/* Day headers */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)',
        gap: '4px', marginBottom: '4px',
      }}>
        {DAY_HEADERS.map((d) => (
          <div
            key={d}
            style={{
              textAlign: 'center',
              fontSize: '0.72rem',
              fontWeight: 700,
              color: '#8C9097',
              textTransform: 'uppercase',
              letterSpacing: '0.5px',
              padding: '4px 0',
            }}
          >
            {d}
          </div>
        ))}
      </div>

      {/* Calendar grid */}
      {loading ? (
        <div style={{ padding: '40px', textAlign: 'center', color: '#8C9097', fontSize: '0.9rem' }}>
          Загрузка...
        </div>
      ) : (
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)',
          gap: '4px',
        }}>
          {calendarDays.map((date, idx) => (
            <DayCell
              key={idx}
              date={date}
              orders={orders}
              isCurrentMonth={date.getMonth() === month}
              isToday={isSameDay(date, today)}
              isSelected={isSameDay(date, selectedDate)}
              onSelect={setSelectedDate}
              isMobile={isMobile}
            />
          ))}
        </div>
      )}

      {/* Day detail panel */}
      <div style={{ marginTop: '28px' }}>
        <h3 style={{
          fontFamily: 'var(--font-heading)', fontWeight: 700,
          fontSize: '0.95rem', marginBottom: '14px',
          color: '#1E1E2D',
          textTransform: 'capitalize',
        }}>
          {selectedDateLabel}
        </h3>
        {loading ? null : <DayDetail date={selectedDate} orders={orders} />}
      </div>
    </div>
  );
};

export default CalendarPage;
