import { useState, useEffect, useRef } from 'react';
import { ChevronLeft, ChevronRight, Plus, Link2, Search, X } from 'lucide-react';
import { useCalendar } from './useCalendar';
import { useIsMobile } from '../../hooks/useIsMobile';
import OrderModal from '../orders/OrderModal';
import { supabase } from '../../lib/supabase';

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, onClick }) {
  const color = getStatusColor(order.status);
  const isOverdue = order.scheduled_at &&
    new Date(order.scheduled_at) < new Date() &&
    order.status !== 'закрыт';
  return (
    <div
      onClick={(e) => { e.stopPropagation(); onClick(order); }}
      title={isOverdue ? `Просрочено: ${order.name}` : `${order.name} — ${order.status}`}
      style={{
        background: isOverdue ? '#fef2f2' : color + '1A',
        color: isOverdue ? '#ef4444' : color,
        fontSize: '0.68rem',
        fontWeight: 600,
        padding: '2px 6px',
        borderRadius: '4px',
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        maxWidth: '100%',
        lineHeight: 1.4,
        cursor: 'pointer',
      }}
    >
      {order.name}
    </div>
  );
}

function DayCell({ date, orders, isCurrentMonth, isToday, isSelected, onSelect, onOrderClick, 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} onClick={onOrderClick} />
      ))}

      {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 OrderPicker({ date, onAssign, onClose }) {
  const [query, setQuery] = useState('');
  const [allOrders, setAllOrders] = useState([]);
  const [loading, setLoading] = useState(true);
  const [assigning, setAssigning] = useState(null);
  const inputRef = useRef(null);

  useEffect(() => {
    let isMounted = true;
    supabase.from('orders')
      .select('id, name, phone, status, scheduled_at')
      .order('created_at', { ascending: false })
      .then(({ data }) => { if (isMounted) { setAllOrders(data ?? []); setLoading(false); } });
    return () => { isMounted = false; };
  }, []);

  useEffect(() => { inputRef.current?.focus(); }, []);

  const q = query.trim().toLowerCase();
  const filtered = q
    ? allOrders.filter((o) =>
        o.name?.toLowerCase().includes(q) || o.phone?.toLowerCase().includes(q)
      )
    : allOrders;

  const handleAssign = async (order) => {
    setAssigning(order.id);
    // Set time to noon on the selected date
    const d = new Date(date);
    d.setHours(12, 0, 0, 0);
    await supabase.from('orders').update({ scheduled_at: d.toISOString() }).eq('id', order.id);
    onAssign();
  };

  const dateLabel = date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long' });

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(0,0,0,0.4)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '16px',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: '#fff', borderRadius: '16px', width: '100%', maxWidth: '460px',
          boxShadow: '0 8px 40px rgba(0,0,0,0.18)', overflow: 'hidden',
          display: 'flex', flexDirection: 'column', maxHeight: '80vh',
        }}
      >
        {/* Header */}
        <div style={{ padding: '20px 20px 16px', borderBottom: '1px solid #E9ECEF', flexShrink: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
            <div>
              <div style={{ fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: '1rem' }}>
                Привязать заявку
              </div>
              <div style={{ fontSize: '0.78rem', color: '#8C9097', marginTop: '2px' }}>
                к {dateLabel}
              </div>
            </div>
            <button
              onClick={onClose}
              style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#8C9097', padding: '4px' }}
            >
              <X size={18} />
            </button>
          </div>
          <div style={{ position: 'relative' }}>
            <Search size={15} style={{ position: 'absolute', left: '10px', top: '50%', transform: 'translateY(-50%)', color: '#8C9097', pointerEvents: 'none' }} />
            <input
              ref={inputRef}
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Имя или телефон..."
              style={{
                width: '100%', padding: '9px 12px 9px 34px',
                border: '1.5px solid #E9ECEF', borderRadius: '8px',
                fontSize: '0.88rem', outline: 'none', boxSizing: 'border-box',
                fontFamily: 'var(--font-body)',
              }}
              onFocus={(e) => e.target.style.borderColor = '#4361EE'}
              onBlur={(e) => e.target.style.borderColor = '#E9ECEF'}
            />
          </div>
        </div>

        {/* List */}
        <div style={{ overflowY: 'auto', flex: 1 }}>
          {loading && (
            <div style={{ padding: '24px', textAlign: 'center', color: '#8C9097', fontSize: '0.85rem' }}>
              Загрузка...
            </div>
          )}
          {!loading && filtered.length === 0 && (
            <div style={{ padding: '24px', textAlign: 'center', color: '#8C9097', fontSize: '0.85rem' }}>
              Ничего не найдено
            </div>
          )}
          {filtered.map((o) => {
            const color = getStatusColor(o.status);
            const busy = assigning === o.id;
            return (
              <div
                key={o.id}
                onClick={() => !assigning && handleAssign(o)}
                style={{
                  padding: '12px 20px',
                  display: 'flex', alignItems: 'center', gap: '12px',
                  borderBottom: '1px solid #F3F4F6',
                  cursor: assigning ? 'wait' : 'pointer',
                  opacity: assigning && !busy ? 0.5 : 1,
                  transition: 'background 0.1s',
                }}
                onMouseEnter={(e) => { if (!assigning) e.currentTarget.style.background = '#F5F7FA'; }}
                onMouseLeave={(e) => e.currentTarget.style.background = ''}
              >
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: '0.9rem', marginBottom: '2px' }}>{o.name}</div>
                  <div style={{ fontSize: '0.75rem', color: '#8C9097' }}>
                    {o.phone}
                    {o.scheduled_at && (
                      <span style={{ marginLeft: '8px' }}>
                        · сейчас: {new Date(o.scheduled_at).toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' })}
                      </span>
                    )}
                  </div>
                </div>
                <span style={{
                  background: color + '1A', color,
                  fontSize: '0.7rem', fontWeight: 700,
                  padding: '2px 8px', borderRadius: '10px',
                  textTransform: 'uppercase', letterSpacing: '0.3px', flexShrink: 0,
                }}>
                  {busy ? '...' : o.status}
                </span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

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

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
      {dayOrders.length === 0 && (
        <div style={{ color: 'var(--text-muted, #8C9097)', fontSize: '0.85rem' }}>
          На этот день записей нет
        </div>
      )}
      {dayOrders.map((o) => {
        const color = getStatusColor(o.status);
        const time = new Date(o.scheduled_at).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
        const isOverdue = o.scheduled_at &&
          new Date(o.scheduled_at) < new Date() &&
          o.status !== 'закрыт';
        return (
          <div
            key={o.id}
            onClick={() => onOrderClick(o)}
            className="glass-panel"
            style={{
              padding: '12px 16px',
              borderLeft: `3px solid ${isOverdue ? '#ef4444' : color}`,
              background: isOverdue ? '#fffafa' : undefined,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              gap: '12px',
              cursor: 'pointer',
              transition: 'box-shadow 0.15s',
            }}
            onMouseEnter={(e) => e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.1)'}
            onMouseLeave={(e) => e.currentTarget.style.boxShadow = ''}
          >
            <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: isOverdue ? '#ef4444' : 'var(--text-muted, #8C9097)', fontWeight: isOverdue ? 700 : undefined }}>
                {isOverdue ? `⚠ Просрочено` : time}
              </span>
            </div>
          </div>
        );
      })}
      <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', marginTop: '4px' }}>
        <button
          onClick={onAdd}
          className="btn-primary"
          style={{ display: 'inline-flex', alignItems: 'center', gap: '6px' }}
        >
          <Plus size={15} />
          Новая заявка
        </button>
        <button
          onClick={onAssign}
          style={{
            display: 'inline-flex', alignItems: 'center', gap: '6px',
            padding: '8px 16px', borderRadius: '8px', cursor: 'pointer',
            background: 'transparent', border: '1.5px solid #E9ECEF',
            fontSize: '0.88rem', fontWeight: 600, color: '#1E1E2D',
            fontFamily: 'var(--font-heading)',
          }}
          onMouseEnter={(e) => e.currentTarget.style.borderColor = '#4361EE'}
          onMouseLeave={(e) => e.currentTarget.style.borderColor = '#E9ECEF'}
        >
          <Link2 size={15} />
          Привязать заявку
        </button>
      </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 [editOrder, setEditOrder] = useState(null);
  const [createDate, setCreateDate] = useState(null);
  const [showPicker, setShowPicker] = useState(false);
  const isMobile = useIsMobile();
  const { orders, loading, refetch } = useCalendar(year, month);

  const handleModalClose = () => { setEditOrder(null); setCreateDate(null); };
  const handleModalSaved = () => { handleModalClose(); refetch(); };

  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}
              onOrderClick={setEditOrder}
              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}
            onOrderClick={setEditOrder}
            onAdd={() => setCreateDate(selectedDate)}
            onAssign={() => setShowPicker(true)}
          />
        )}
      </div>

      {editOrder && (
        <OrderModal
          order={editOrder}
          mode="edit"
          onClose={handleModalClose}
          onSaved={handleModalSaved}
        />
      )}

      {createDate && (
        <OrderModal
          order={{ scheduled_at: createDate.toISOString() }}
          mode="create"
          onClose={handleModalClose}
          onSaved={handleModalSaved}
        />
      )}

      {showPicker && (
        <OrderPicker
          date={selectedDate}
          onAssign={() => { setShowPicker(false); refetch(); }}
          onClose={() => setShowPicker(false)}
        />
      )}
    </div>
  );
};

export default CalendarPage;
