'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { logoutUser } from '@/lib/actions/auth';
import { getOfflineTxs, deleteOfflineTx } from '@/lib/offline-db';

interface NavigationShellProps {
  children: React.ReactNode;
  user: {
    _id: string;
    email: string;
    role: 'SUPER_ADMIN' | 'CITY_HEAD' | 'AREA_INCHARGE' | 'MEMBER';
  };
}

export const NavigationShell: React.FC<NavigationShellProps> = ({ children, user }) => {
  const pathname = usePathname();
  const router = useRouter();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);

  const handleLogout = async () => {
    try {
      const txs = await getOfflineTxs();
      const userPending = txs.filter(t => t.userId === user._id && t.status === 'Pending Sync');

      if (userPending.length > 0) {
        const discard = window.confirm(
          `You have ${userPending.length} unsynced offline attendance check-ins.\n\n` +
          "Do you want to DISCARD these unsynced transactions and logout?\n" +
          "Click OK to discard and logout, or Cancel to remain logged in and sync them."
        );
        if (!discard) {
          return;
        }
        for (const tx of userPending) {
          await deleteOfflineTx(tx.syncId);
        }
      }

      // Cleanup remaining synced transactions for this user
      const remainingTxs = txs.filter(t => t.userId === user._id);
      for (const tx of remainingTxs) {
        await deleteOfflineTx(tx.syncId);
      }
    } catch (err) {
      console.error('Failed to cleanup offline queue on logout:', err);
    }

    await logoutUser();
    router.push('/login');
    router.refresh();
  };

  const menuItems = [
    { name: 'Dashboard', href: '/dashboard', roles: ['SUPER_ADMIN', 'CITY_HEAD', 'AREA_INCHARGE'] },
    { name: 'Satsangs & Calendar', href: '/satsangs', roles: ['SUPER_ADMIN', 'CITY_HEAD', 'AREA_INCHARGE'] },
    { name: 'Members Directory', href: '/members', roles: ['SUPER_ADMIN', 'CITY_HEAD', 'AREA_INCHARGE'] },
    { name: 'Attendance Reports', href: '/reports/attendance', roles: ['SUPER_ADMIN', 'CITY_HEAD', 'AREA_INCHARGE'] },
    { name: 'Geography & Centers', href: '/geography', roles: ['SUPER_ADMIN', 'CITY_HEAD'] },
    { name: 'User Management', href: '/users', roles: ['SUPER_ADMIN'] },
    { name: 'System Settings', href: '/settings', roles: ['SUPER_ADMIN'] }
  ];

  const allowedItems = menuItems.filter((item) => item.roles.includes(user.role));

  const linkClass = (href: string) => {
    const base = 'flex items-center px-4 py-3 text-base font-medium rounded-lg transition-all touch-target ';
    const isActive = pathname === href || pathname.startsWith(href + '/');
    return isActive
      ? base + 'bg-brand-primary text-white shadow-sm'
      : base + 'text-gray-600 hover:bg-gray-100 hover:text-gray-900';
  };

  return (
    <div className="flex h-screen bg-brand-background overflow-hidden">
      {/* Desktop Sidebar */}
      <aside className="hidden md:flex md:flex-col md:w-64 bg-white border-r border-gray-200">
        {/* Branding header */}
        <div className="flex items-center h-16 px-6 border-b border-gray-200 gap-3">
          <div className="h-8 w-8 rounded-full bg-brand-primary flex items-center justify-center text-white font-bold text-lg shadow-sm">
            G
          </div>
          <div>
            <span className="font-semibold text-gray-900 tracking-tight block">GeetaShyam.guru</span>
            <span className="text-xs text-brand-secondary font-medium">Satsang Parivar CRM</span>
          </div>
        </div>

        {/* Navigation list */}
        <nav className="flex-1 px-4 py-6 space-y-1 overflow-y-auto">
          {allowedItems.map((item) => (
            <Link key={item.name} href={item.href} className={linkClass(item.href)}>
              {item.name}
            </Link>
          ))}
        </nav>

        {/* User profile details & Logout */}
        <div className="p-4 border-t border-gray-200">
          <div className="flex flex-col mb-4">
            <span className="text-sm font-semibold text-gray-900 truncate">{user.email}</span>
            <span className="text-xs font-medium text-brand-secondary tracking-wider uppercase">
              {user.role.replace('_', ' ')}
            </span>
          </div>
          <button
            onClick={handleLogout}
            className="w-full touch-target px-4 py-2 text-sm font-medium text-red-600 border border-red-200 rounded-lg bg-red-50 hover:bg-red-100 hover:border-red-300 transition-colors"
          >
            Sign Out
          </button>
        </div>
      </aside>

      {/* Main content wrapper */}
      <div className="flex flex-col flex-1 overflow-hidden">
        {/* Mobile Header */}
        <header className="flex items-center justify-between h-16 px-4 bg-white border-b border-gray-200 md:hidden">
          <div className="flex items-center gap-3">
            <button
              onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
              className="touch-target p-2 text-gray-500 hover:text-gray-900 focus:outline-none"
              aria-label="Open sidebar menu"
            >
              <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 6h16M4 12h16M4 18h16" />
              </svg>
            </button>
            <span className="font-semibold text-gray-900 tracking-tight">GeetaShyam.guru</span>
          </div>
          <span className="text-xs font-semibold px-2.5 py-1 rounded bg-brand-primary bg-opacity-10 text-brand-primary uppercase">
            {user.role.substring(0, 5)}
          </span>
        </header>

        {/* Mobile Sidebar overlay */}
        {isMobileMenuOpen && (
          <div className="fixed inset-0 z-50 flex md:hidden">
            <div className="fixed inset-0 bg-gray-600 bg-opacity-75" onClick={() => setIsMobileMenuOpen(false)} />
            
            <aside className="relative flex flex-col w-full max-w-xs bg-white h-full border-r border-gray-200 shadow-xl animate-slide-in">
              <div className="flex items-center justify-between h-16 px-6 border-b border-gray-200">
                <span className="font-semibold text-gray-900">GeetaShyam.guru</span>
                <button
                  onClick={() => setIsMobileMenuOpen(false)}
                  className="touch-target p-2 text-gray-500 hover:text-gray-900 focus:outline-none"
                  aria-label="Close menu"
                >
                  <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>

              <nav className="flex-1 px-4 py-6 space-y-1 overflow-y-auto">
                {allowedItems.map((item) => (
                  <Link
                    key={item.name}
                    href={item.href}
                    onClick={() => setIsMobileMenuOpen(false)}
                    className={linkClass(item.href)}
                  >
                    {item.name}
                  </Link>
                ))}
              </nav>

              <div className="p-4 border-t border-gray-200">
                <div className="flex flex-col mb-4">
                  <span className="text-sm font-semibold text-gray-900 truncate">{user.email}</span>
                  <span className="text-xs font-medium text-brand-secondary uppercase">{user.role.replace('_', ' ')}</span>
                </div>
                <button
                  onClick={handleLogout}
                  className="w-full touch-target px-4 py-2 text-sm font-medium text-red-600 border border-red-200 rounded-lg bg-red-50 hover:bg-red-100 transition-colors"
                >
                  Sign Out
                </button>
              </div>
            </aside>
          </div>
        )}

        {/* Content body */}
        <main className="flex-1 relative overflow-y-auto focus:outline-none bg-brand-background p-4 md:p-8">
          {children}
        </main>
      </div>
    </div>
  );
};

export default NavigationShell;
