'use client';

import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { ReactNode, useState, useEffect, useCallback } from 'react';
import { Home, Plus, Package, LogOut, Search, Menu, X, Users, Bell, MessageSquare, Truck } from 'lucide-react';
import { FeedbackWidget } from './feedback-widget';
import { useDeliveryNotifications, useNotificationUpdates, DeliveryNotification } from '../hooks/use-delivery-notifications';

type InboxNotification = {
  id: string;
  title: string;
  body: string;
  url?: string;
  ts: number;
  read: boolean;
  type?: 'push' | 'first_delivery' | 'new_delivery';
};

interface MobileLayoutProps {
  children: ReactNode;
  title?: string;
  className?: string;
}

export function MobileLayout({ children, title, className = '' }: MobileLayoutProps) {
  const pathname = usePathname();
  const router = useRouter();
  const [showMenu, setShowMenu] = useState(false);
  const [showSearch, setShowSearch] = useState(false);
  const [showNotifications, setShowNotifications] = useState(false);
  const [isFeedbackOpen, setIsFeedbackOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [notifications, setNotifications] = useState<InboxNotification[]>([]);
  
  // Initialize delivery notifications service
  const deliveryNotifications = useDeliveryNotifications(true);

  const unreadCount = notifications.reduce((acc, n) => acc + (n.read ? 0 : 1), 0);

  const loadNotifications = useCallback(() => {
    try {
      const raw = localStorage.getItem('gcx_fshs_notifications');
      if (!raw) return [] as InboxNotification[];
      const parsed = JSON.parse(raw);
      if (!Array.isArray(parsed)) return [] as InboxNotification[];
      
      // Transform delivery notifications to inbox format
      return parsed.map((n: any) => ({
        id: n.id,
        title: n.title,
        body: n.body || n.message,
        url: n.url || (n.deliveryId ? `/field-staff/my-deliveries/${n.deliveryId}` : '/field-staff'),
        ts: n.ts || (n.createdAt ? new Date(n.createdAt).getTime() : Date.now()),
        read: n.read ?? false,
        type: n.type || 'push',
      })) as InboxNotification[];
    } catch {
      return [] as InboxNotification[];
    }
  }, []);

  const saveNotifications = (items: InboxNotification[]) => {
    try {
      localStorage.setItem('gcx_fshs_notifications', JSON.stringify(items));
    } catch {
      // ignore
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('gcx_fshs_token');
    localStorage.removeItem('gcx_fshs_user');
    window.location.href = '/login';
  };

  const navItems = [
    { href: '/field-staff', label: 'Home', icon: Home },
    { href: '/field-staff/suppliers', label: 'Suppliers', icon: Users },
    { href: '/field-staff/new-delivery', label: 'New', icon: Plus, isCenter: true },
    { href: '/field-staff/my-deliveries', label: 'History', icon: Package },
  ];

  const isNavItemActive = (href: string) =>
    href === '/field-staff' ? pathname === href : pathname.startsWith(href);

  const quickActions = [
    {
      label: 'Record New Delivery',
      action: () => {
        router.push('/field-staff/new-delivery');
        setShowSearch(false);
      },
      keywords: ['new', 'delivery', 'create', 'record', 'add'],
    },
    {
      label: 'View Dashboard',
      action: () => {
        router.push('/field-staff');
        setShowSearch(false);
      },
      keywords: ['dashboard', 'home', 'stats'],
    },
    {
      label: 'My Deliveries',
      action: () => {
        router.push('/field-staff/my-deliveries');
        setShowSearch(false);
      },
      keywords: ['deliveries', 'history', 'my'],
    },
    {
      label: 'Supplier Directory',
      action: () => {
        router.push('/field-staff/suppliers');
        setShowSearch(false);
      },
      keywords: ['suppliers', 'contacts', 'phone', 'directory'],
    },
    {
      label: 'Logout',
      action: () => {
        handleLogout();
        setShowSearch(false);
      },
      keywords: ['logout', 'exit', 'sign out'],
    },
  ];

  const filteredActions = searchQuery
    ? quickActions.filter((action) =>
        action.keywords.some((keyword) =>
          keyword.toLowerCase().includes(searchQuery.toLowerCase())
        ) || action.label.toLowerCase().includes(searchQuery.toLowerCase())
      )
    : quickActions;

  // Keyboard shortcut: Ctrl+K
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        setShowSearch(true);
        setShowMenu(false);
        setShowNotifications(false);
      }
      if (e.key === 'Escape') {
        setShowSearch(false);
        setShowMenu(false);
        setShowNotifications(false);
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, []);

  // Load notifications on mount and listen for updates
  useEffect(() => {
    setNotifications(loadNotifications());
    
    // Listen for notification updates from the delivery service
    const handleNotificationUpdate = () => {
      setNotifications(loadNotifications());
    };
    
    window.addEventListener('notifications-updated', handleNotificationUpdate);
    return () => window.removeEventListener('notifications-updated', handleNotificationUpdate);
  }, [loadNotifications]);

  useEffect(() => {
    if (typeof window === 'undefined') return;
    if (!('serviceWorker' in navigator)) return;

    const handler = (event: MessageEvent) => {
      const data = event.data;
      if (!data || data.type !== 'PUSH_NOTIFICATION') return;

      const payload = data.payload || {};
      const title = typeof payload.title === 'string' && payload.title ? payload.title : 'GCX FSHS';
      const body = typeof payload.body === 'string' && payload.body ? payload.body : 'You have a new update.';
      const url = typeof payload.url === 'string' && payload.url ? payload.url : '/field-staff';
      const ts = typeof payload.ts === 'number' ? payload.ts : Date.now();

      setNotifications((prev) => {
        const newNotification: InboxNotification = {
          id: `${ts}-${Math.random().toString(16).slice(2)}`,
          title,
          body,
          url,
          ts,
          read: false,
          type: 'push' as const,
        };
        const next: InboxNotification[] = [newNotification, ...prev].slice(0, 50);
        saveNotifications(next);
        return next;
      });
    };

    navigator.serviceWorker.addEventListener('message', handler);
    return () => navigator.serviceWorker.removeEventListener('message', handler);
  }, []);

  useEffect(() => {
    if (!showNotifications) return;
    // Mark all as read when the panel is opened
    setNotifications((prev) => {
      const next = prev.map((n) => ({ ...n, read: true }));
      saveNotifications(next);
      return next;
    });
  }, [showNotifications]);

  return (
    <div className={`flex min-h-screen max-w-full flex-col overflow-x-hidden bg-gradient-to-b from-slate-100 via-slate-50 to-white pb-32 ${className}`}>
      {/* Mobile Header */}
      <header
        className="fixed inset-x-0 top-0 z-40 px-3"
        style={{ paddingTop: 'max(0.75rem, env(safe-area-inset-top))' }}
      >
        <div className="mx-auto max-w-lg">
        <div className="flex min-h-16 items-center justify-between rounded-[1.35rem] border border-white/70 bg-white/[0.78] px-3 py-2 shadow-[0_12px_32px_rgba(15,23,42,0.14)] backdrop-blur-2xl backdrop-saturate-150 dark:border-white/10 dark:bg-slate-900/[0.78]">
          <Link
            href="/field-staff"
            aria-label="GCX Field Staff home"
            className="relative flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl border border-white/80 bg-white/90 shadow-[0_7px_18px_rgba(15,23,42,0.12)] ring-1 ring-slate-200/60 transition hover:-translate-y-0.5 active:scale-95 dark:border-white/10 dark:bg-slate-800/90 dark:ring-white/10"
          >
            <img src="/icon-192.png" alt="" className="h-8 w-8 object-contain" />
            <span className="absolute -bottom-1 left-1/2 grid h-1 w-7 -translate-x-1/2 grid-cols-3 overflow-hidden rounded-full shadow-sm ring-2 ring-white dark:ring-slate-900" aria-hidden="true">
              <span className="bg-red-600" />
              <span className="bg-yellow-500" />
              <span className="bg-green-600" />
            </span>
          </Link>
          
          <div className="flex items-center gap-2">
            {/* Search Button */}
            <button
              onClick={() => setShowSearch(true)}
              onMouseDown={() => {
                setShowMenu(false);
                setShowNotifications(false);
              }}
              className="flex h-10 w-10 items-center justify-center rounded-xl border border-white/70 bg-white/60 text-slate-600 shadow-sm transition hover:bg-white/90 hover:text-emerald-700 active:scale-95 dark:border-white/10 dark:bg-slate-800/70 dark:text-slate-200"
              title="Search (Ctrl+K)"
              aria-label="Open search"
            >
              <Search className="h-5 w-5" />
            </button>

            {/* Notifications */}
            <button
              onClick={() => {
                setShowNotifications((v) => !v);
                setShowMenu(false);
                setShowSearch(false);
              }}
              className="relative flex h-10 w-10 items-center justify-center rounded-xl border border-white/70 bg-white/60 text-slate-600 shadow-sm transition hover:bg-white/90 hover:text-emerald-700 active:scale-95 dark:border-white/10 dark:bg-slate-800/70 dark:text-slate-200"
              aria-label="Open notifications"
              title="Notifications"
            >
              <Bell className="h-5 w-5" />
              {unreadCount > 0 && (
                <span className="absolute -right-1 -top-1 inline-flex min-w-5 items-center justify-center rounded-full bg-rose-500 px-1.5 text-[10px] font-bold text-white">
                  {unreadCount > 9 ? '9+' : unreadCount}
                </span>
              )}
            </button>

            {/* Menu Toggle */}
            <button
              onClick={() => setShowMenu(!showMenu)}
              onMouseDown={() => {
                setShowSearch(false);
                setShowNotifications(false);
              }}
              className={`flex h-10 w-10 items-center justify-center rounded-xl border shadow-sm transition active:scale-95 ${
                showMenu
                  ? 'border-emerald-500/20 bg-emerald-600 text-white'
                  : 'border-white/70 bg-white/60 text-slate-600 hover:bg-white/90 hover:text-emerald-700 dark:border-white/10 dark:bg-slate-800/70 dark:text-slate-200'
              }`}
              aria-label={showMenu ? "Close menu" : "Open menu"}
            >
              {showMenu ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
            </button>
          </div>
        </div>

        {/* Notifications Panel */}
        {showNotifications && (
          <div className="mt-2 animate-fade-in overflow-hidden rounded-[1.35rem] border border-white/70 bg-white/[0.9] shadow-[0_18px_45px_rgba(15,23,42,0.18)] backdrop-blur-2xl dark:border-white/10 dark:bg-slate-900/[0.9]">
            <div className="flex items-center justify-between border-b border-slate-200 px-4 py-3">
              <div>
                <div className="text-sm font-semibold text-slate-900">Notifications</div>
                <div className="text-xs text-slate-500">Latest updates</div>
              </div>
              <button
                onClick={() => setShowNotifications(false)}
                aria-label="Close notifications"
                className="rounded-lg p-2 text-slate-500 hover:bg-slate-100"
              >
                <X className="h-4 w-4" />
              </button>
            </div>
            <div className="max-h-80 overflow-y-auto p-2">
              {notifications.length === 0 ? (
                <div className="py-8 text-center text-sm text-slate-500">No notifications yet</div>
              ) : (
                notifications.map((n) => (
                  <button
                    key={n.id}
                    onClick={() => {
                      setShowNotifications(false);
                      router.push(n.url || '/field-staff');
                    }}
                    className="w-full rounded-xl px-3 py-3 text-left transition hover:bg-slate-50"
                  >
                    <div className="flex items-start gap-3">
                      {/* Show truck icon for delivery notifications, dot for others */}
                      {n.type === 'first_delivery' ? (
                        <div className="mt-0.5 flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-emerald-100">
                          <Truck className="h-3.5 w-3.5 text-emerald-600" />
                        </div>
                      ) : (
                        <div className="mt-1 h-2 w-2 flex-shrink-0 rounded-full bg-emerald-500" />
                      )}
                      <div className="min-w-0 flex-1">
                        <div className="truncate text-sm font-semibold text-slate-900">{n.title}</div>
                        <div className="mt-0.5 line-clamp-2 text-xs text-slate-600">{n.body}</div>
                        <div className="mt-1 text-[10px] text-slate-400">
                          {new Date(n.ts).toLocaleString()}
                        </div>
                      </div>
                    </div>
                  </button>
                ))
              )}
            </div>
          </div>
        )}

        {/* Dropdown Menu */}
        {showMenu && (
          <div className="mt-2 animate-fade-in overflow-hidden rounded-[1.35rem] border border-white/70 bg-white/[0.9] shadow-[0_18px_45px_rgba(15,23,42,0.18)] backdrop-blur-2xl dark:border-white/10 dark:bg-slate-900/[0.9]">
            <nav className="space-y-1 p-3">
              {navItems.map((item) => {
                const Icon = item.icon;
                const isActive = isNavItemActive(item.href);
                return (
                  <button
                    key={item.href}
                    onClick={() => {
                      router.push(item.href);
                      setShowMenu(false);
                    }}
                    className={`flex w-full items-center gap-3 rounded-xl px-4 py-3.5 text-left transition ${
                      isActive 
                        ? 'bg-emerald-50 text-emerald-700 font-medium' 
                        : 'text-slate-700 hover:bg-slate-50'
                    }`}
                  >
                    <div className={`rounded-lg p-2 ${isActive ? 'bg-emerald-100' : 'bg-slate-100'}`}>
                      <Icon className="h-5 w-5" />
                    </div>
                    <span>{item.label}</span>
                  </button>
                );
              })}
              <hr className="my-3 border-slate-200" />
              <button
                onClick={() => {
                  setIsFeedbackOpen(true);
                  setShowMenu(false);
                }}
                className="flex w-full items-center gap-3 rounded-xl px-4 py-3.5 text-left text-slate-700 transition hover:bg-slate-50"
              >
                <div className="rounded-lg bg-slate-100 p-2">
                  <MessageSquare className="h-5 w-5" />
                </div>
                <span>Report Issue</span>
              </button>
              <button
                onClick={handleLogout}
                className="flex w-full items-center gap-3 rounded-xl px-4 py-3.5 text-left text-rose-600 transition hover:bg-rose-50"
              >
                <div className="rounded-lg bg-rose-100 p-2">
                  <LogOut className="h-5 w-5" />
                </div>
                <span>Logout</span>
              </button>
            </nav>
          </div>
        )}
        </div>
      </header>

      {/* Main Content */}
      <main
        className="max-w-full flex-1 overflow-auto overflow-x-hidden"
        style={{ paddingTop: 'calc(5.5rem + env(safe-area-inset-top))' }}
      >
        {title && <h1 className="sr-only">{title}</h1>}
        {children}
      </main>

      {/* Bottom Navigation */}
      <nav
        className="pointer-events-none fixed inset-x-0 bottom-0 z-50 px-3"
        style={{ paddingBottom: 'max(0.75rem, env(safe-area-inset-bottom))' }}
        aria-label="Primary navigation"
      >
        <div className="pointer-events-auto mx-auto grid max-w-md grid-cols-4 items-end gap-1 rounded-[1.6rem] border border-white/70 bg-white/[0.78] px-2 py-2 shadow-[0_16px_45px_rgba(15,23,42,0.22)] backdrop-blur-2xl backdrop-saturate-150 dark:border-white/10 dark:bg-slate-900/[0.8]">
          {navItems.map((item) => {
            const Icon = item.icon;
            const isActive = isNavItemActive(item.href);

            if (item.isCenter) {
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  aria-current={isActive ? 'page' : undefined}
                  className="flex h-14 min-w-0 flex-col items-center justify-end rounded-2xl px-2 pb-1 text-emerald-700 transition active:scale-95 dark:text-emerald-300"
                >
                  <div className={`-mt-7 flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl bg-emerald-600 text-white shadow-[0_10px_24px_rgba(5,150,105,0.38)] ring-4 transition-all hover:-translate-y-0.5 ${
                    isActive ? 'ring-emerald-100 dark:ring-emerald-900' : 'ring-white/80 dark:ring-slate-800/90'
                  }`}>
                    <Icon className="h-6 w-6" />
                  </div>
                  <span className="mt-1 text-[10px] font-bold leading-none">{item.label}</span>
                </Link>
              );
            }

            return (
              <Link
                key={item.href}
                href={item.href}
                aria-current={isActive ? 'page' : undefined}
                className={`flex h-14 min-w-0 flex-col items-center justify-center gap-1 rounded-2xl px-1 transition-all ${
                  isActive
                    ? 'bg-emerald-600 text-white shadow-[0_8px_20px_rgba(5,150,105,0.24)]'
                    : 'text-slate-500 hover:bg-white/70 hover:text-slate-800 active:bg-white/90 dark:text-slate-400 dark:hover:bg-slate-800/80 dark:hover:text-white'
                }`}
              >
                <Icon className="h-5 w-5 shrink-0" />
                <span className={`max-w-full truncate text-[10px] leading-none ${isActive ? 'font-bold' : 'font-semibold'}`}>
                  {item.label}
                </span>
              </Link>
            );
          })}
        </div>
      </nav>

      {/* Search Overlay (Command Palette) */}
      {showSearch && (
        <div className="fixed inset-0 z-50 flex items-start justify-center bg-black/50 p-4 pt-20 backdrop-blur-sm">
          <div className="w-full max-w-lg animate-slide-in-top rounded-xl border border-slate-200 bg-white shadow-2xl">
            {/* Search Input */}
            <div className="flex items-center gap-3 border-b border-slate-200 px-4 py-3">
              <Search className="h-5 w-5 text-slate-400" />
              <input
                type="text"
                placeholder="Search actions or type command..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                autoFocus
                className="flex-1 bg-transparent text-sm outline-none placeholder:text-slate-400"
              />
              <button
                onClick={() => {
                  setShowSearch(false);
                  setSearchQuery('');
                }}
                className="text-xs text-slate-500"
              >
                <kbd className="rounded bg-slate-100 px-2 py-1 text-xs font-semibold">Esc</kbd>
              </button>
            </div>

            {/* Quick Actions */}
            <div className="max-h-80 overflow-y-auto p-2">
              {filteredActions.length === 0 ? (
                <div className="py-8 text-center text-sm text-slate-500">
                  No actions found
                </div>
              ) : (
                filteredActions.map((action, index) => (
                  <button
                    key={index}
                    onClick={action.action}
                    className="flex w-full items-center gap-3 rounded-lg px-4 py-3 text-left text-sm transition hover:bg-slate-100"
                  >
                    <span className="text-slate-700">{action.label}</span>
                  </button>
                ))
              )}
            </div>

            {/* Footer Hint */}
            <div className="border-t border-slate-200 px-4 py-2 text-center text-xs text-slate-500">
              Press <kbd className="rounded bg-slate-100 px-1.5 py-0.5 font-semibold">Ctrl+K</kbd> anytime to search
            </div>
          </div>
        </div>
      )}
      <FeedbackWidget isOpen={isFeedbackOpen} onClose={() => setIsFeedbackOpen(false)} />
    </div>
  );
}
