import { useState, useEffect } from 'react';
import { Outlet, useLocation } from 'react-router-dom';
import { Plus, Menu, Bell, BellOff } from 'lucide-react';
import Sidebar from './Sidebar';
import { supabase } from '../../lib/supabase';
import { useIsMobile } from '../../hooks/useIsMobile';
import { usePushNotifications } from '../../hooks/usePushNotifications';

const PAGE_TITLES = {
  '/admin/kanban': 'Канбан',
  '/admin/analytics': 'Аналитика',
  '/admin/completed': 'Завершённые заказы',
};

const AdminLayout = () => {
  const location = useLocation();
  const title = PAGE_TITLES[location.pathname] || 'Панель управления';
  const [showNewOrder, setShowNewOrder] = useState(false);
  const [newCount, setNewCount] = useState(0);
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const isMobile = useIsMobile();
  const { supported: pushSupported, subscribed: pushSubscribed, loading: pushLoading, subscribe: pushSubscribe, unsubscribe: pushUnsubscribe } = usePushNotifications();

  useEffect(() => {
    const refreshBadge = () => {
      supabase
        .from('orders')
        .select('id', { count: 'exact', head: true })
        .eq('status', 'новая')
        .then(({ count }) => setNewCount(count || 0));
    };

    refreshBadge();
    const channel = supabase
      .channel('badge-count')
      .on('postgres_changes', { event: '*', schema: 'public', table: 'orders' }, refreshBadge)
      .subscribe();
    return () => supabase.removeChannel(channel);
  }, []);

  useEffect(() => {
    setSidebarOpen(false);
  }, [location.pathname]);

  return (
    <div className="admin-panel" style={{ display: 'flex', minHeight: '100vh' }}>
      {isMobile && sidebarOpen && (
        <div
          onClick={() => setSidebarOpen(false)}
          style={{
            position: 'fixed', inset: 0,
            background: 'rgba(0,0,0,0.4)',
            zIndex: 99,
          }}
        />
      )}
      <Sidebar
        isOpen={sidebarOpen}
        onClose={() => setSidebarOpen(false)}
        isMobile={isMobile}
      />
      <div style={{
        marginLeft: isMobile ? 0 : '240px',
        flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0,
      }}>
        {/* Header */}
        <header style={{
          height: '60px', background: '#fff',
          borderBottom: '1px solid #E9ECEF',
          display: 'flex', alignItems: 'center',
          justifyContent: 'space-between', padding: '0 28px',
          position: 'sticky', top: 0, zIndex: 50,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
            {isMobile && (
              <button
                onClick={() => setSidebarOpen(true)}
                aria-label="Открыть меню"
                style={{
                  background: 'none', border: 'none', cursor: 'pointer',
                  color: 'var(--text-main)', padding: '4px', display: 'flex',
                }}
              >
                <Menu size={22} />
              </button>
            )}
            <h1 style={{ fontFamily: 'var(--font-heading)', fontSize: '1.05rem', fontWeight: 700, color: 'var(--text-main)' }}>
              {title}
            </h1>
            {newCount > 0 && (
              <span
                aria-label={`${newCount} новых заявок`}
                style={{
                  background: '#ef4444', color: '#fff',
                  borderRadius: '50px', padding: '2px 9px',
                  fontSize: '0.72rem', fontWeight: 700,
                }}
              >
                {newCount} новых
              </span>
            )}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            {pushSupported && (
              <button
                onClick={pushSubscribed ? pushUnsubscribe : pushSubscribe}
                disabled={pushLoading}
                title={pushSubscribed ? 'Отключить уведомления' : 'Включить уведомления'}
                aria-label={pushSubscribed ? 'Отключить push-уведомления' : 'Включить push-уведомления'}
                style={{
                  background: pushSubscribed ? 'rgba(67,97,238,0.08)' : 'none',
                  border: '1.5px solid var(--border-light)',
                  borderRadius: '8px',
                  padding: '7px',
                  cursor: pushLoading ? 'not-allowed' : 'pointer',
                  color: pushSubscribed ? '#4361EE' : 'var(--text-muted)',
                  display: 'flex',
                  alignItems: 'center',
                  opacity: pushLoading ? 0.6 : 1,
                  transition: 'opacity 0.15s, background 0.15s, color 0.15s',
                }}
              >
                {pushSubscribed ? <Bell size={16} /> : <BellOff size={16} />}
              </button>
            )}
            <button
              onClick={() => setShowNewOrder(true)}
              className="btn-primary"
              style={{ padding: '8px 18px', fontSize: '0.88rem', display: 'flex', alignItems: 'center', gap: '7px' }}
            >
              <Plus size={15} />
              Заявка
            </button>
          </div>
        </header>

        {/* Page content */}
        <main style={{ flex: 1, padding: '28px', overflow: 'auto' }}>
          <Outlet context={{ showNewOrder, setShowNewOrder }} />
        </main>
      </div>
    </div>
  );
};

export default AdminLayout;
