import { useState, useEffect } from 'react';
import { Outlet, useLocation } from 'react-router-dom';
import { Plus } from 'lucide-react';
import Sidebar from './Sidebar';
import { supabase } from '../../lib/supabase';

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);

  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);
  }, []);

  return (
    <div className="admin-panel" style={{ display: 'flex', minHeight: '100vh' }}>
      <Sidebar />
      <div style={{ marginLeft: '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' }}>
            <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>
          <button
            onClick={() => setShowNewOrder(true)}
            className="btn-primary"
            style={{ padding: '8px 18px', fontSize: '0.88rem', display: 'flex', alignItems: 'center', gap: '7px' }}
          >
            <Plus size={15} />
            Заявка
          </button>
        </header>

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

export default AdminLayout;
