import { Outlet, Link, useNavigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import api from '../lib/api';
import {
  LayoutDashboard,
  PhoneCall,
  Settings,
  BookOpen,
  LogOut,
  Bell,
  Search,
  Menu,
  ChevronDown,
  Globe,
  Calendar,
  Mic,
  Building2,
  CreditCard,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { useState, useEffect } from 'react';

interface OrgCompany {
  _id: string;
  companyName: string;
}

const Layout = () => {
  const { logout, user } = useAuthStore();
  const navigate = useNavigate();
  const location = useLocation();
  const [tenantDropdownOpen, setTenantDropdownOpen] = useState(false);
  const [companies, setCompanies] = useState<OrgCompany[]>([]);
  const [activeCompanyName, setActiveCompanyName] = useState('Organization');

  useEffect(() => {
    let active = true;
    api
      .get<OrgCompany[]>('/company')
      .then((res) => {
        if (!active) return;
        setCompanies(res.data || []);
        if (res.data && res.data.length > 0) {
          setActiveCompanyName(res.data[0].companyName);
        }
      })
      .catch(() => {});
    return () => {
      active = false;
    };
  }, [location.pathname]);

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  const navItems = [
    { name: 'Overview', path: '/dashboard', icon: LayoutDashboard },
    { name: 'Voice Simulator', path: '/simulator', icon: Mic },
    { name: 'Appointments', path: '/appointments', icon: Calendar },
    { name: 'Call Logs', path: '/calls', icon: PhoneCall },
    { name: 'Knowledge Base', path: '/knowledge-base', icon: BookOpen },
    { name: 'Companies & Agents', path: '/company-registration', icon: Building2 },
    { name: 'Integrations & CRM', path: '/crm', icon: Settings },
    { name: 'Billing, Team & GDPR', path: '/billing', icon: CreditCard },
  ];

  return (
    <div className="flex h-screen bg-slate-50 text-slate-900 overflow-hidden font-sans">
      {/* Light Theme Sidebar */}
      <motion.div
        initial={{ x: -250 }}
        animate={{ x: 0 }}
        className="w-72 bg-white border-r border-slate-200 flex flex-col z-20 shadow-xs relative"
      >
        <div className="p-6 flex items-center gap-3 border-b border-slate-100">
          <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-indigo-600 via-indigo-500 to-purple-600 flex items-center justify-center text-white shadow-md shadow-indigo-500/20 border border-indigo-400/30 shrink-0">
            <svg viewBox="0 0 64 64" fill="none" className="w-6 h-6 text-white">
              <path
                d="M32 8L52 17V31C52 44.5 43.4 55.6 32 59C20.6 55.6 12 44.5 12 31V17L32 8Z"
                fill="currentColor"
                fillOpacity="0.22"
                stroke="currentColor"
                strokeWidth="3.5"
              />
              <path
                d="M22 31V35M27 24V42M32 17V49M37 24V42M42 29V37"
                stroke="currentColor"
                strokeWidth="4"
                strokeLinecap="round"
              />
            </svg>
          </div>
          <div>
            <span className="text-xl font-extrabold tracking-tight text-slate-900 block leading-none">
              Churchill <span className="text-indigo-600">AI</span>
            </span>
            <span className="text-[10px] uppercase tracking-widest text-indigo-600 font-bold block mt-0.5">
              Autonomous Voice Cloud
            </span>
          </div>
        </div>

        <nav className="flex-1 mt-4 px-4 overflow-y-auto">
          <p className="px-4 text-[11px] font-bold uppercase tracking-wider text-slate-400 mb-3">
            Command Center
          </p>
          <ul className="space-y-1">
            {navItems.map((item) => {
              const Icon = item.icon;
              const isActive = location.pathname.startsWith(item.path);
              return (
                <li key={item.name}>
                  <Link
                    to={item.path}
                    className={`relative flex items-center px-4 py-3 rounded-xl transition-all duration-200 group ${
                      isActive
                        ? 'text-indigo-700 font-bold bg-indigo-50 border border-indigo-200/80 shadow-2xs'
                        : 'text-slate-600 hover:text-slate-900 hover:bg-slate-100/80 font-medium'
                    }`}
                  >
                    <Icon
                      className={`w-5 h-5 mr-3 transition-colors ${
                        isActive ? 'text-indigo-600' : 'text-slate-400 group-hover:text-slate-700'
                      }`}
                    />
                    <span className="text-sm">{item.name}</span>
                  </Link>
                </li>
              );
            })}
          </ul>
        </nav>

        <div className="p-4 mx-4 mb-4 rounded-2xl bg-slate-50 border border-slate-200 relative overflow-hidden">
          <div className="flex items-center gap-3 relative z-10">
            <div className="w-10 h-10 rounded-full bg-indigo-600 flex items-center justify-center text-white font-bold shadow-xs">
              {user?.name?.charAt(0) || 'A'}
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-bold text-slate-900 truncate">
                {user?.name || 'Admin User'}
              </p>
              <p className="text-xs text-slate-500 truncate">
                {user?.email || 'admin@example.com'}
              </p>
            </div>
          </div>
          <button
            onClick={handleLogout}
            className="mt-3 flex items-center justify-center w-full px-4 py-2 text-xs font-semibold text-rose-600 hover:text-rose-700 hover:bg-rose-50 rounded-xl transition-colors border border-rose-200/60"
          >
            <LogOut className="w-4 h-4 mr-2" />
            <span>Sign Out</span>
          </button>
        </div>
      </motion.div>

      {/* Main Content Area */}
      <div className="flex-1 flex flex-col min-w-0 overflow-hidden relative bg-slate-50">
        {/* Top Navbar */}
        <header className="h-[72px] flex items-center justify-between px-8 backdrop-blur-xl bg-white/90 border-b border-slate-200 z-10 sticky top-0">
          <div className="flex items-center gap-6">
            <button className="lg:hidden text-slate-600 hover:text-slate-900 transition-colors">
              <Menu className="w-6 h-6" />
            </button>

            {/* Tenant Switcher */}
            <div className="relative">
              <button
                onClick={() => setTenantDropdownOpen(!tenantDropdownOpen)}
                className="flex items-center gap-2.5 px-3.5 py-2 rounded-xl bg-slate-50 hover:bg-slate-100 transition-colors border border-slate-200"
              >
                <div className="w-6 h-6 rounded-lg bg-indigo-50 border border-indigo-200 flex items-center justify-center">
                  <Globe className="w-3.5 h-3.5 text-indigo-600" />
                </div>
                <span className="text-sm font-semibold text-slate-800">{activeCompanyName}</span>
                <ChevronDown className="w-4 h-4 text-slate-500" />
              </button>

              <AnimatePresence>
                {tenantDropdownOpen && (
                  <motion.div
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: 10 }}
                    className="absolute top-full mt-2 w-64 bg-white border border-slate-200 rounded-2xl shadow-xl overflow-hidden z-50"
                  >
                    <div className="px-4 py-2.5 border-b border-slate-100 bg-slate-50">
                      <span className="text-[11px] font-bold text-slate-500 uppercase tracking-wider">
                        Registered Tenants
                      </span>
                    </div>
                    <div className="p-1.5 max-h-60 overflow-y-auto">
                      {companies.map((c) => (
                        <button
                          key={c._id}
                          onClick={() => {
                            setActiveCompanyName(c.companyName);
                            setTenantDropdownOpen(false);
                          }}
                          className={`w-full text-left px-3 py-2 rounded-xl text-sm font-semibold flex items-center gap-2 transition-colors ${
                            activeCompanyName === c.companyName
                              ? 'bg-indigo-50 text-indigo-700'
                              : 'hover:bg-slate-100 text-slate-700'
                          }`}
                        >
                          <div
                            className={`w-2 h-2 rounded-full ${
                              activeCompanyName === c.companyName ? 'bg-indigo-600' : 'bg-slate-300'
                            }`}
                          />
                          <span className="truncate">{c.companyName}</span>
                        </button>
                      ))}
                      <button
                        onClick={() => {
                          setTenantDropdownOpen(false);
                          navigate('/company-registration');
                        }}
                        className="w-full text-left px-3 py-2 mt-1 border-t border-slate-100 text-xs text-indigo-600 hover:bg-indigo-50 rounded-lg font-bold"
                      >
                        + Manage Companies &amp; Agents
                      </button>
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          </div>

          <div className="flex items-center gap-4">
            <div className="relative hidden md:block">
              <Search className="w-4 h-4 absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400" />
              <input
                type="text"
                placeholder="Search call logs & summaries..."
                onKeyDown={(e) => {
                  if (e.key === 'Enter') navigate('/calls');
                }}
                className="pl-9 pr-4 py-2 bg-slate-50 border border-slate-200 rounded-full text-sm text-slate-800 w-64 transition-all focus:ring-2 focus:ring-indigo-500/30 outline-none placeholder:text-slate-400"
              />
            </div>

            <div className="h-6 w-px bg-slate-200 mx-1" />

            <button
              onClick={() => navigate('/appointments')}
              title="View Appointments"
              className="relative p-2 text-slate-500 hover:text-indigo-600 transition-colors rounded-full hover:bg-slate-100"
            >
              <Bell className="w-5 h-5" />
              <span className="absolute top-1.5 right-1.5 w-2 h-2 bg-indigo-600 rounded-full border border-white" />
            </button>
          </div>
        </header>

        <main className="flex-1 overflow-auto p-8 z-0">
          <div className="max-w-7xl mx-auto">
            <AnimatePresence mode="wait">
              <motion.div
                key={location.pathname}
                initial={{ opacity: 0, y: 8 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -8 }}
                transition={{ duration: 0.25 }}
              >
                <Outlet />
              </motion.div>
            </AnimatePresence>
          </div>
        </main>
      </div>
    </div>
  );
};

export default Layout;
