import { useState } from 'react';
import { DndContext, closestCorners, DragOverlay, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { useOutletContext } from 'react-router-dom';
import { useOrders } from './useOrders';
import { useAuth } from '../auth/useAuth';
import { useIsMobile } from '../../hooks/useIsMobile';
import KanbanColumn from './KanbanColumn';
import OrderCard from './OrderCard';
import OrderModal from './OrderModal';

const STATUSES = ['новая', 'замер', 'согласование', 'монтаж', 'закрыт'];

const KanbanBoard = () => {
  const { ordersByStatus, loading, updateStatus } = useOrders();
  const { session } = useAuth();
  const { showNewOrder, setShowNewOrder } = useOutletContext() || {};
  const isMobile = useIsMobile();
  const [activeOrder, setActiveOrder] = useState(null);
  const [selectedOrder, setSelectedOrder] = useState(null);

  const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));

  const [localOverrides, setLocalOverrides] = useState({});

  const findOrderStatus = (orderId) => {
    if (localOverrides[orderId]) return localOverrides[orderId];
    for (const status of STATUSES) {
      if (ordersByStatus[status]?.find((o) => o.id === orderId)) return status;
    }
    return null;
  };

  const handleDragStart = ({ active }) => {
    const status = findOrderStatus(active.id);
    if (status) setActiveOrder(ordersByStatus[status].find((o) => o.id === active.id) ||
      Object.values(ordersByStatus).flat().find((o) => o.id === active.id));
  };

  const handleDragEnd = async ({ active, over }) => {
    setActiveOrder(null);
    if (!over) return;

    const targetStatus = STATUSES.includes(over.id) ? over.id : findOrderStatus(over.id);
    const sourceStatus = findOrderStatus(active.id);

    if (targetStatus && sourceStatus !== targetStatus) {
      setLocalOverrides((prev) => ({ ...prev, [active.id]: targetStatus }));
      const { error } = await updateStatus(active.id, targetStatus, session?.user?.email);
      if (error) {
        console.error('Status update failed:', error);
        setLocalOverrides((prev) => {
          const next = { ...prev };
          delete next[active.id];
          return next;
        });
      } else {
        setLocalOverrides((prev) => {
          const next = { ...prev };
          delete next[active.id];
          return next;
        });
      }
    }
  };

  const effectiveOrdersByStatus = STATUSES.reduce((acc, status) => {
    acc[status] = (ordersByStatus[status] || []).filter(
      (o) => !localOverrides[o.id] || localOverrides[o.id] === status
    );
    // Add orders that were moved here optimistically
    const overrideOrders = Object.entries(localOverrides)
      .filter(([, s]) => s === status)
      .map(([id]) => Object.values(ordersByStatus).flat().find((o) => o.id === id))
      .filter(Boolean);
    acc[status] = [...acc[status], ...overrideOrders];
    return acc;
  }, {});

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '60px', color: 'var(--text-muted)', fontFamily: 'var(--font-heading)' }}>
        Загрузка заказов...
      </div>
    );
  }

  return (
    <>
      <DndContext sensors={sensors} collisionDetection={closestCorners} onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
        <div style={{
          display: 'flex',
          gap: '14px',
          alignItems: 'flex-start',
          overflowX: isMobile ? 'auto' : 'visible',
          WebkitOverflowScrolling: 'touch',
          paddingBottom: isMobile ? '12px' : '20px',
          minWidth: 'min-content',
        }}>
          {STATUSES.map((status) => (
            <KanbanColumn
              key={status}
              status={status}
              orders={effectiveOrdersByStatus[status] || []}
              onCardClick={setSelectedOrder}
              isMobile={isMobile}
            />
          ))}
        </div>
        <DragOverlay>
          {activeOrder && <OrderCard order={activeOrder} onClick={() => {}} />}
        </DragOverlay>
      </DndContext>

      {selectedOrder && (
        <OrderModal
          order={selectedOrder}
          mode="edit"
          onClose={() => setSelectedOrder(null)}
          onSaved={() => setSelectedOrder(null)}
        />
      )}

      {showNewOrder && (
        <OrderModal
          order={null}
          mode="create"
          onClose={() => setShowNewOrder(false)}
          onSaved={() => setShowNewOrder(false)}
        />
      )}
    </>
  );
};

export default KanbanBoard;
