import { Link, useLocation, Outlet } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { useSocket } from '../context/SocketContext';
import { Menu, X, Bell, User, LogOut, Search, Home, Briefcase, MessageSquare, CreditCard } from 'lucide-react';
import { useState } from 'react';

export default function Layout() {
  const { user, logout } = useAuth();
  const { unreadCount } = useSocket();
  const location = useLocation();
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [userMenuOpen, setUserMenuOpen] = useState(false);

  const navLinks = [
    { path: '/', label: 'Home', icon: Home },
    { path: '/services', label: 'Services', icon: Briefcase },
  ];

  if (user) {
    navLinks.push(
      { path: '/dashboard', label: 'My Bookings', icon: MessageSquare },
      { path: '/profile', label: 'Profile', icon: User }
    );
  }

  return (
    <div className="min-h-screen flex flex-col">
      <header className="bg-white border-b border-gray-200 sticky top-0 z-50">
        <nav className="container" aria-label="Main navigation">
          <div className="flex items-center justify-between h-16">
            <Link to="/" className="flex items-center gap-2 text-xl font-bold text-primary-600" aria-label="Handyman Home">
              <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>
              <span>Handyman</span>
            </Link>

            <div className="hidden md:flex items-center gap-6">
              {navLinks.map(({ path, label, icon: Icon }) => (
                <Link key={path} to={path} className={`flex items-center gap-2 text-sm font-medium transition-colors ${location.pathname === path ? 'text-primary-600' : 'text-gray-600 hover:text-primary-600'}`}>
                  <Icon className="w-5 h-5" />
                  {label}
                </Link>
              ))}
            </div>

            <div className="hidden md:flex items-center gap-4">
              <Link to="/search" className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input type="search" placeholder="Search services..." className="pl-10 pr-4 py-2 bg-gray-100 border-0 rounded-full text-sm w-64 focus:outline-none focus:ring-2 focus:ring-primary-500" />
              </Link>

              {user ? (
                <div className="relative">
                  <button onClick={() => setUserMenuOpen(!userMenuOpen)} className="flex items-center gap-2 p-1 rounded-full hover:bg-gray-100" aria-expanded={userMenuOpen} aria-haspopup="true">
                    <div className="w-8 h-8 rounded-full bg-primary-100 flex items-center justify-center">
                      {user.avatar ? <img src={user.avatar} alt="" className="w-8 h-8 rounded-full" /> : <span className="text-primary-600 font-medium">{user.name?.[0]?.toUpperCase()}</span>}
                    </div>
                    <span className="hidden sm:block text-sm font-medium">{user.name}</span>
                  </button>
                  {userMenuOpen && (
                    <div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-100 py-1 z-50">
                      <Link to="/dashboard" className="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50" onClick={() => setUserMenuOpen(false)}><MessageSquare className="w-4 h-4" /> My Bookings</Link>
                      <Link to="/notifications" className="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 relative" onClick={() => setUserMenuOpen(false)}>
                        <Bell className="w-4 h-4" />
                        Notifications
                        {unreadCount > 0 && <span className="ml-auto bg-primary-600 text-white text-xs rounded-full px-2 py-0.5">{unreadCount}</span>}
                      </Link>
                      <Link to="/profile" className="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50" onClick={() => setUserMenuOpen(false)}><User className="w-4 h-4" /> Profile</Link>
                      <hr className="my-1 border-gray-100" />
                      <button onClick={logout} className="flex items-center gap-2 w-full px-4 py-2 text-sm text-red-600 hover:bg-red-50"><LogOut className="w-4 h-4" /> Logout</button>
                    </div>
                  )}
                </div>
              ) : (
                <div className="flex items-center gap-3">
                  <Link to="/login" className="btn-secondary text-sm">Login</Link>
                  <Link to="/register" className="btn-primary text-sm">Sign Up</Link>
                </div>
              )}
            </div>

            <button className="md:hidden p-2 rounded-lg hover:bg-gray-100" onClick={() => setMobileMenuOpen(!mobileMenuOpen)} aria-expanded={mobileMenuOpen} aria-controls="mobile-menu" aria-label="Toggle menu">
              {mobileMenuOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
            </button>
          </div>

          {mobileMenuOpen && (
            <div id="mobile-menu" className="md:hidden py-4 border-t border-gray-100">
              <div className="flex flex-col gap-2 mb-4">
                {navLinks.map(({ path, label, icon: Icon }) => (
                  <Link key={path} to={path} className={`flex items-center gap-3 px-3 py-2 rounded-lg ${location.pathname === path ? 'bg-primary-50 text-primary-600' : 'text-gray-600 hover:bg-gray-50'}`} onClick={() => setMobileMenuOpen(false)}>
                    <Icon className="w-5 h-5" />
                    {label}
                  </Link>
                ))}
              </div>
              {user ? (
                <div className="space-y-2">
                  <Link to="/dashboard" className="flex items-center gap-3 px-3 py-2 rounded-lg text-gray-600 hover:bg-gray-50" onClick={() => setMobileMenuOpen(false)}><MessageSquare className="w-5 h-5" /> My Bookings</Link>
                  <Link to="/notifications" className="flex items-center gap-3 px-3 py-2 rounded-lg text-gray-600 hover:bg-gray-50 relative" onClick={() => setMobileMenuOpen(false)}>
                    <Bell className="w-5 h-5" />
                    Notifications {unreadCount > 0 && <span className="ml-auto bg-primary-600 text-white text-xs rounded-full px-2 py-0.5">{unreadCount}</span>}
                  </Link>
                  <Link to="/profile" className="flex items-center gap-3 px-3 py-2 rounded-lg text-gray-600 hover:bg-gray-50" onClick={() => setMobileMenuOpen(false)}><User className="w-5 h-5" /> Profile</Link>
                  <button onClick={logout} className="flex items-center gap-3 w-full px-3 py-2 rounded-lg text-red-600 hover:bg-red-50"><LogOut className="w-5 h-5" /> Logout</button>
                </div>
              ) : (
                <div className="flex flex-col gap-2">
                  <Link to="/login" className="btn-secondary text-center" onClick={() => setMobileMenuOpen(false)}>Login</Link>
                  <Link to="/register" className="btn-primary text-center" onClick={() => setMobileMenuOpen(false)}>Sign Up</Link>
                </div>
              )}
            </div>
          )}
        </nav>
      </header>

      <main className="flex-1">
        <Outlet />
      </main>

      <footer className="bg-gray-900 text-gray-400 py-12">
        <div className="container grid grid-cols-1 md:grid-cols-4 gap-8">
          <div>
            <h3 className="text-white font-bold text-lg mb-4">Handyman</h3>
            <p className="text-sm leading-relaxed">Your trusted platform for on-demand home services. Connect with verified professionals.</p>
          </div>
          <div>
            <h4 className="text-white font-semibold mb-4">Services</h4>
            <ul className="space-y-2 text-sm">
              <li><Link to="/services?category=plumbing" className="hover:text-white">Plumbing</Link></li>
              <li><Link to="/services?category=electrical" className="hover:text-white">Electrical</Link></li>
              <li><Link to="/services?category=carpentry" className="hover:text-white">Carpentry</Link></li>
              <li><Link to="/services?category=cleaning" className="hover:text-white">Cleaning</Link></li>
            </ul>
          </div>
          <div>
            <h4 className="text-white font-semibold mb-4">Support</h4>
            <ul className="space-y-2 text-sm">
              <li><a href="#" className="hover:text-white">Help Center</a></li>
              <li><a href="#" className="hover:text-white">Contact Us</a></li>
              <li><a href="#" className="hover:text-white">FAQ</a></li>
            </ul>
          </div>
          <div>
            <h4 className="text-white font-semibold mb-4">Legal</h4>
            <ul className="space-y-2 text-sm">
              <li><a href="#" className="hover:text-white">Terms of Service</a></li>
              <li><a href="#" className="hover:text-white">Privacy Policy</a></li>
            </ul>
          </div>
        </div>
        <div className="container mt-8 pt-8 border-t border-gray-800 text-center text-sm">
          © {new Date().getFullYear()} Handyman. All rights reserved.
        </div>
      </footer>
    </div>
  );
}