import React, { useState, useEffect, useCallback, useRef, PropsWithChildren } from 'react';
import { Head, Link, usePage, router } from '@inertiajs/react';
import { PageProps } from '@/types';
import { PosNotification } from '@/types/notifications';
import {
  ShoppingCart, FileText, Clock, Trash2, DollarSign, Package, User,
  BarChart3, Tag, Store, SlidersHorizontal, Heart, LogOut,
  PanelLeftClose, PanelLeftOpen, ChevronDown, Bell, ShoppingBag, CheckCircle2,
  AlertTriangle, Info, AlertCircle, CheckCheck, Loader2
} from '@/Components/AnimatedIcons';
import { usePosContext } from '@/Contexts/PosContext';
import axios from 'axios';

export default function PosLayout({ children }: PropsWithChildren) {
  const { auth } = usePage<PageProps>().props;
  const user = (auth as any)?.user;
  
  const { 
    sidebarCollapsed, setSidebarCollapsed,
    cart, setShowCart
  } = usePosContext();

  // Real-time Clock
  const [currentTime, setCurrentTime] = useState<string>('');
  const [currentDate, setCurrentDate] = useState<string>('');
  
  // Notification bell — badge comes from Inertia share; list is fetched on-demand
  const [showNotifications, setShowNotifications] = useState(false);
  const [notificationsLoading, setNotificationsLoading] = useState(false);
  const [notifications, setNotifications] = useState<PosNotification[]>([]);
  // Local unread count — starts from Inertia shared value, decrements on client mark-read
  const [unreadCount, setUnreadCount] = useState<number>(user?.unread_notifications_count ?? 0);
  const bellRef = useRef<HTMLDivElement>(null);

  const fetchNotifications = useCallback(async () => {
    setNotificationsLoading(true);
    try {
      const res = await axios.get('/api/v1/notifications', {
        params: { per_page: 10 },
        headers: { Accept: 'application/json' },
      });
      setNotifications(res.data?.data?.data ?? []);
    } catch {
      // Silently fail — bell opens but shows empty state
    } finally {
      setNotificationsLoading(false);
    }
  }, []);

  const openBell = () => {
    setShowNotifications(true);
    fetchNotifications();
  };

  const closeBell = () => setShowNotifications(false);

  const markAsRead = async (id: string) => {
    try {
      await axios.post(`/api/v1/notifications/${id}/read`, {}, { headers: { Accept: 'application/json' } });
      setNotifications(prev => prev.map(n => n.id === id ? { ...n, read_at: new Date().toISOString() } : n));
      setUnreadCount(prev => Math.max(0, prev - 1));
    } catch { /* Silently ignore */ }
  };

  const markAllAsRead = async () => {
    try {
      await axios.post('/api/v1/notifications/read-all', {}, { headers: { Accept: 'application/json' } });
      setNotifications(prev => prev.map(n => ({ ...n, read_at: n.read_at ?? new Date().toISOString() })));
      setUnreadCount(0);
    } catch { /* Silently ignore */ }
  };

  // Close bell on Escape key
  useEffect(() => {
    if (!showNotifications) return;
    const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') closeBell(); };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [showNotifications]);

  // Update unread count when Inertia navigates (badge refreshes from server)
  useEffect(() => {
    setUnreadCount(user?.unread_notifications_count ?? 0);
  }, [user?.unread_notifications_count]);

  const severityIcon = (severity: string) => {
    switch (severity) {
      case 'SUCCESS':  return <CheckCheck className="w-4 h-4 text-emerald-500" aria-hidden="true" />;
      case 'WARNING':  return <AlertTriangle className="w-4 h-4 text-amber-500" aria-hidden="true" />;
      case 'ERROR':    return <AlertCircle className="w-4 h-4 text-rose-500" aria-hidden="true" />;
      case 'CRITICAL': return <AlertCircle className="w-4 h-4 text-red-600" aria-hidden="true" />;
      default:         return <Info className="w-4 h-4 text-blue-500" aria-hidden="true" />;
    }
  };

  const severityDot = (severity: string) => {
    const colors: Record<string, string> = {
      SUCCESS: 'bg-emerald-400', WARNING: 'bg-amber-400',
      ERROR: 'bg-rose-500', CRITICAL: 'bg-red-600', INFO: 'bg-blue-400',
    };
    return colors[severity] || 'bg-slate-400';
  };

  useEffect(() => {
    const updateTime = () => {
      const now = new Date();
      setCurrentDate(
        now.toLocaleDateString('en-US', {
          weekday: 'short',
          day: '2-digit',
          month: 'short',
          year: 'numeric',
        })
      );
      setCurrentTime(
        now.toLocaleTimeString('en-US', {
          hour: '2-digit',
          minute: '2-digit',
          hour12: true,
        })
      );
    };
    updateTime();
    const interval = setInterval(updateTime, 1000);
    return () => clearInterval(interval);
  }, []);

  const navLink = (href: string, title: string, Icon: React.ElementType, label: string) => (
    <Link
      href={href}
      className={`flex items-center ${sidebarCollapsed ? 'justify-center p-3 w-12' : 'space-x-3 px-4 py-2.5'} rounded-2xl text-slate-600 hover:text-slate-900 hover:bg-slate-100 transition-colors text-sm font-medium`}
      title={title}
    >
      <Icon className="w-4 h-4 flex-shrink-0" />
      {!sidebarCollapsed && <span>{label}</span>}
    </Link>
  );

  const sectionLabel = (full: string, short: string) => (
    <div className={`pt-4 pb-1 ${sidebarCollapsed ? 'px-1 flex justify-center w-full' : 'px-4'}`}>
      <span className={`text-[10px] font-bold uppercase tracking-wider text-slate-400 ${sidebarCollapsed ? 'text-[8px]' : ''}`}>
        {sidebarCollapsed ? short : full}
      </span>
    </div>
  );

  return (
    <div className="min-h-screen bg-[#F4F5F9] text-slate-800 flex font-sans antialiased selection:bg-[#FF0D8F] selection:text-white">
      {/* 1. LEFT LIGHT SIDEBAR */}
      <aside className={`bg-white text-slate-800 flex flex-col justify-between flex-shrink-0 min-h-screen border-r border-slate-200 z-20 transition-all duration-300 ${sidebarCollapsed ? 'w-20 items-center' : 'w-64'}`}>
        <div className="w-full">
          {/* Brand */}
          <div className={`p-5 pb-2 flex items-center ${sidebarCollapsed ? 'justify-center flex-col space-y-3' : 'justify-between'}`}>
            <div className={`flex items-center ${sidebarCollapsed ? 'justify-center' : 'space-x-3'}`}>
              <div className="w-10 h-10 rounded-full bg-white flex items-center justify-center text-[#9D1739] shadow-sm border border-slate-100 flex-shrink-0">
                <svg className="w-6 h-6 fill-current text-[#9D1739]" viewBox="0 0 24 24">
                  <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
                </svg>
              </div>
              {!sidebarCollapsed && (
                <div>
                  <h1 className="font-serif italic text-2xl font-bold text-[#9D1739] tracking-tight leading-none">Laya's</h1>
                  <span className="text-[9px] font-extrabold uppercase tracking-widest text-slate-500 block mt-0.5">CAKES &amp; CANDLES</span>
                </div>
              )}
            </div>
            <button onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className={`text-slate-400 hover:text-slate-700 transition-colors ${sidebarCollapsed ? 'mt-2' : ''}`} title="Toggle Sidebar">
              {sidebarCollapsed ? <PanelLeftOpen className="w-5 h-5" /> : <PanelLeftClose className="w-5 h-5" />}
            </button>
          </div>

          <nav className={`px-4 mt-6 space-y-1 ${sidebarCollapsed ? 'flex flex-col items-center w-full' : ''}`}>
            <Link href={route('pos.index')} className={`flex items-center ${sidebarCollapsed ? 'justify-center p-3' : 'space-x-3 px-4 py-3'} rounded-2xl bg-[#FDF1F3] text-[#9D1739] font-bold text-sm transition-transform active:scale-95`} title="POS Terminal">
              <ShoppingCart className="w-5 h-5 text-[#9D1739] flex-shrink-0" />
              {!sidebarCollapsed && <span className="tracking-wide">POS Terminal</span>}
            </Link>

            {navLink(route('invoices.index'), 'Invoices', FileText, 'Invoices')}
            {navLink(route('daily-closing.index'), 'Daily Closing', Clock, 'Daily Closing')}
            {navLink(route('wastage.index'), 'Wastage Register', Trash2, 'Wastage Register')}
            {navLink(route('expenses.index'), 'Expenses', DollarSign, 'Expenses')}

            {sectionLabel('BUSINESS', 'BIZ')}
            {navLink(route('admin.products.index'), 'Products', Package, 'Products')}
            {navLink(route('admin.customers.index'), 'Customers', User, 'Customers')}
            {navLink(route('admin.reports.index'), 'Reports', BarChart3, 'Reports')}

            {sectionLabel('BRANCH', 'BR')}
            {navLink(route('branch.dashboard'), 'Branch Operations', Store, 'Branch Operations')}
            {navLink(route('branch.dashboard'), 'Settings', SlidersHorizontal, 'Settings')}
          </nav>
        </div>

        <div className={`p-4 space-y-3 ${sidebarCollapsed ? 'flex flex-col items-center w-full' : ''}`}>
          {!sidebarCollapsed && (
            <div className="flex flex-col items-center justify-center p-4">
              <p className="font-serif italic text-lg font-bold text-slate-700 leading-tight text-center">Sweet treats<br />Stronger moments</p>
              <Heart className="w-5 h-5 text-[#9D1739] mt-2 mb-4" />
              <div className="w-16 h-16 bg-[url('https://images.unsplash.com/photo-1578985545062-69928b1d9587?w=100&q=80')] bg-cover bg-center rounded-full opacity-40 mix-blend-multiply"></div>
            </div>
          )}

          {!sidebarCollapsed && (
            <p className="text-left text-[10px] text-slate-400 font-medium leading-relaxed mt-4">
              © 2026 Laya's Cakes &amp; Candles<br />v1.0.0
            </p>
          )}
        </div>
      </aside>

      {/* 2. MAIN CENTER CONTENT AREA */}
      <main className="flex-1 flex flex-col overflow-y-auto min-w-0 p-5 space-y-4">
        
        {/* TOP HEADER BAR */}
        <header className="flex items-center justify-between gap-4">
          {/* Location Pill */}
          <div className="flex items-center space-x-2 bg-white border border-slate-200/90 px-3.5 py-2.5 rounded-2xl shadow-sm cursor-pointer hover:border-slate-300 flex-1 max-w-xs">
            <svg className="w-4 h-4 text-[#FF0D8F] flex-shrink-0" fill="currentColor" viewBox="0 0 24 24">
              <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z" />
            </svg>
            <span className="text-xs font-bold text-slate-800 truncate flex-1">
              {user?.branch?.name || 'Main Flagship Store (Connaught Place)'}
            </span>
            <ChevronDown className="w-3.5 h-3.5 text-slate-400 flex-shrink-0" />
          </div>

          {/* Right Side Badges */}
          <div className="flex items-center space-x-3">
            {/* Date & Time */}
            <div className="hidden md:flex flex-col items-end px-1">
              <span className="text-xs font-bold text-slate-800 leading-tight">{currentDate || '...'}</span>
              <span className="text-[10px] font-medium text-slate-500">{currentTime || '...'}</span>
            </div>

            {/* Cart Toggle Button */}
            <button
              type="button"
              onClick={() => setShowCart(true)}
              className="relative p-2.5 bg-white border border-slate-200/90 rounded-2xl shadow-sm text-slate-600 hover:text-[#FF0D8F] transition-colors"
              title="View Cart"
            >
              <ShoppingBag className="w-4 h-4" />
              {cart && cart.length > 0 && (
                <span className="absolute -top-1 -right-1 min-w-[18px] h-[18px] bg-[#FF0D8F] text-white text-[9px] font-bold rounded-full flex items-center justify-center px-1 shadow-sm">
                  {cart.reduce((sum: number, item: any) => sum + item.quantity, 0)}
                </span>
              )}
            </button>

            {/* Notification Bell */}
            <div className="relative" ref={bellRef}>
              <button
                type="button"
                id="pos-notification-bell"
                onClick={() => showNotifications ? closeBell() : openBell()}
                aria-label={`Notifications${unreadCount > 0 ? `, ${unreadCount} unread` : ''}`}
                aria-expanded={showNotifications}
                aria-haspopup="true"
                className={`relative p-2.5 bg-white border rounded-2xl shadow-sm transition-colors ${showNotifications ? 'border-[#FF0D8F] text-[#FF0D8F]' : 'border-slate-200/90 text-slate-600 hover:text-slate-900'}`}
              >
                <Bell className="w-4 h-4" aria-hidden="true" />
                {unreadCount > 0 && (
                  <span
                    aria-hidden="true"
                    className="absolute -top-1 -right-1 min-w-[16px] h-4 bg-[#FF0D8F] text-white text-[9px] font-bold rounded-full flex items-center justify-center px-1 shadow-xs"
                  >
                    {unreadCount}
                  </span>
                )}
              </button>

              {/* Dropdown */}
              {showNotifications && (
                <div
                  role="dialog"
                  aria-modal="false"
                  aria-label="Notifications panel"
                  className="absolute right-0 mt-2 w-96 bg-white rounded-2xl shadow-xl border border-slate-200 z-50 overflow-hidden flex flex-col"
                >
                  <div className="p-3 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
                    <h3 className="font-bold text-slate-800 text-sm">Notifications</h3>
                    {unreadCount > 0 && (
                      <button
                        onClick={() => markAllAsRead()}
                        className="text-[10px] font-bold text-[#FF0D8F] hover:text-[#D90978]"
                        aria-label="Mark all notifications as read"
                      >
                        Mark all as read
                      </button>
                    )}
                  </div>
                  <div className="max-h-96 overflow-y-auto divide-y divide-slate-100" role="list" aria-label="Notification list">
                    {notificationsLoading ? (
                      <div className="p-10 text-center">
                        <Loader2 className="w-6 h-6 text-[#FF0D8F] mx-auto animate-spin" aria-hidden="true" />
                        <p className="text-xs text-slate-400 mt-3">Loading…</p>
                      </div>
                    ) : notifications.length > 0 ? (
                      notifications.map((notification: PosNotification) => (
                        <div
                          key={notification.id}
                          role="listitem"
                          className={`p-3.5 hover:bg-slate-50 transition-colors flex items-start gap-3 ${!notification.read_at ? 'bg-[#FDF1F3]/40' : ''}`}
                        >
                          {/* Severity indicator dot — NOT the only signal (icon below also present) */}
                          <div
                            className={`mt-1.5 w-2 h-2 rounded-full flex-shrink-0 ${!notification.read_at ? severityDot(notification.severity) : 'bg-slate-200'}`}
                            aria-hidden="true"
                          />

                          {/* Icon */}
                          <div
                            className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${!notification.read_at ? 'bg-slate-100' : 'bg-slate-50'}`}
                            title={notification.severity}
                          >
                            {severityIcon(notification.severity)}
                          </div>

                          {/* Content */}
                          <div className="flex-1 min-w-0">
                            <p className="text-xs text-slate-800 font-bold leading-tight">{notification.title}</p>
                            <p className="text-[11px] text-slate-500 mt-0.5 leading-snug">{notification.message}</p>
                            <p className="text-[10px] text-slate-400 mt-1">
                              <time dateTime={notification.created_at}>
                                {new Date(notification.created_at).toLocaleString()}
                              </time>
                            </p>
                            {notification.action_url && (
                              <a
                                href={notification.action_url}
                                className="text-[10px] font-bold text-[#FF0D8F] mt-1 block hover:underline focus:outline-none focus:ring-1 focus:ring-[#FF0D8F] rounded"
                              >
                                View →
                              </a>
                            )}
                          </div>

                          {/* Mark read */}
                          {!notification.read_at && (
                            <button
                              onClick={() => markAsRead(notification.id)}
                              className="text-slate-300 hover:text-[#FF0D8F] p-1 flex-shrink-0 rounded focus:outline-none focus:ring-1 focus:ring-[#FF0D8F]"
                              aria-label={`Mark "${notification.title}" as read`}
                            >
                              <CheckCircle2 className="w-4 h-4" aria-hidden="true" />
                            </button>
                          )}
                        </div>
                      ))
                    ) : (
                      <div className="p-10 text-center" role="listitem">
                        <Bell className="w-8 h-8 text-slate-300 mx-auto mb-3 opacity-50" aria-hidden="true" />
                        <p className="text-xs text-slate-500 font-medium">No notifications</p>
                        <p className="text-[10px] text-slate-400 mt-1">You're all caught up!</p>
                      </div>
                    )}
                  </div>
                  {notifications.length > 0 && (
                    <div className="p-3 border-t border-slate-100 bg-slate-50/50">
                      <a
                        href="/invoices"
                        className="text-[10px] font-bold text-[#FF0D8F] hover:text-[#D90978] block text-center focus:outline-none focus:ring-1 focus:ring-[#FF0D8F] rounded"
                      >
                        View all notifications
                      </a>
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* Cashier Pill */}
            <div className="flex items-center space-x-2 bg-white border border-slate-200/90 p-1.5 pr-3 rounded-2xl shadow-sm">
              <div className="w-7 h-7 rounded-full bg-[#FF0D8F] text-white font-bold text-xs flex items-center justify-center">
                {user?.name?.charAt(0) || '?'}
              </div>
              <div className="hidden lg:block text-left">
                <span className="block text-xs font-bold text-slate-800 leading-tight truncate max-w-[100px]">{user?.name || 'Sign In Required'}</span>
                <span className="block text-[9px] font-medium text-slate-400">{user ? (user?.role?.label || 'Cashier') : 'No session'}</span>
              </div>
            </div>
          </div>
        </header>

        {children}

      </main>
    </div>
  );
}
