import React from 'react';
import { 
  Search, 
  Bell, 
  Plus, 
  Moon, 
  Sun, 
  Globe, 
  User, 
  X, 
  Briefcase, 
  Users, 
  CheckSquare, 
  TrendingUp, 
  Ticket, 
  DollarSign,
  FileText, 
  Settings, 
  LogOut,
  Lock,
  History,
  UserPlus,
  Wrench,
  FilePlus,
  Zap
} from 'lucide-react';
import { cn, getInitials } from '@/lib/utils';
import { toast } from 'sonner';
import { motion, AnimatePresence } from 'framer-motion';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/context/AuthContext';
import { useApp } from '@/context/AppContext';

interface TopNavProps {
  onOpenQuickCreate: () => void;
}

export function TopNav({ onOpenQuickCreate }: TopNavProps) {
  const { profile, logout, isAdmin, rolePermissions, hasPermission } = useAuth();
  const { companySettings, projects, tasks, expenses, candidates } = useApp();
  const [isDark, setIsDark] = React.useState(false);
  const [isProfileOpen, setIsProfileOpen] = React.useState(false);
  const [isLanguageOpen, setIsLanguageOpen] = React.useState(false);
  const [isNotificationsOpen, setIsNotificationsOpen] = React.useState(false);
  const [currentLanguage, setCurrentLanguage] = React.useState('English');
  const [readNotificationIds, setReadNotificationIds] = React.useState<string[]>(() => {
    const saved = localStorage.getItem('read_notifications');
    return saved ? JSON.parse(saved) : [];
  });
  const navigate = useNavigate();

  const hasAnyAccess = isAdmin || (profile && (rolePermissions[profile.role] || []).length > 0);
  const isLogged = !!profile;

  const liveNotifications = React.useMemo(() => {
    const list: any[] = [];
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    // 1. Overdue Tasks
    tasks.forEach(task => {
      const dueDate = new Date(task.dueDate);
      if (dueDate < today && task.status !== 'Completed') {
        list.push({
          id: `task-overdue-${task.id}`,
          title: 'Task Overdue',
          description: `Task "${task.title}" was due on ${task.dueDate}`,
          time: 'Overdue',
          type: 'task',
          link: '/tasks'
        });
      }
    });

    // 2. New Projects (last 7 days)
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
    projects.forEach(project => {
      const issueDate = project.issueDate ? new Date(project.issueDate) : null;
      if (issueDate && issueDate >= sevenDaysAgo) {
        list.push({
          id: `project-new-${project.id}`,
          title: 'New Project',
          description: `New project "${project.name}" has been created.`,
          time: project.issueDate,
          type: 'project',
          link: '/projects'
        });
      }
    });

    // 3. Pending Expenses
    expenses.filter(e => e.status === 'Pending').forEach(expense => {
      list.push({
        id: `expense-pending-${expense.id}`,
        title: 'Pending Expense',
        description: `Expense "${expense.description}" requires approval.`,
        time: expense.date,
        type: 'finance',
        link: '/expenses'
      });
    });

    // 4. New Candidates
    candidates.forEach(cand => {
      const appliedDate = new Date(cand.appliedDate);
      if (appliedDate >= sevenDaysAgo) {
        list.push({
          id: `candidate-new-${cand.id}`,
          title: 'New Candidate',
          description: `${cand.name} applied for ${cand.role}`,
          time: cand.appliedDate,
          type: 'crm',
          link: '/recruitment'
        });
      }
    });

    return list.sort((a, b) => {
      if (a.time === 'Overdue') return -1;
      if (b.time === 'Overdue') return 1;
      return new Date(b.time).getTime() - new Date(a.time).getTime();
    }).map(n => ({
      ...n,
      read: readNotificationIds.includes(n.id)
    }));
  }, [tasks, projects, expenses, candidates, readNotificationIds]);

  const unreadCount = liveNotifications.filter(n => !n.read).length;

  const markAsRead = (id: string) => {
    if (!readNotificationIds.includes(id)) {
      const newReadIds = [...readNotificationIds, id];
      setReadNotificationIds(newReadIds);
      localStorage.setItem('read_notifications', JSON.stringify(newReadIds));
    }
  };

  const clearNotifications = () => {
    const allIds = liveNotifications.map(n => n.id);
    setReadNotificationIds(allIds);
    localStorage.setItem('read_notifications', JSON.stringify(allIds));
    setIsNotificationsOpen(false);
    toast.success('All notifications marked as read');
  };

  const languages = [
    { name: 'English', code: 'EN', flag: '🇺🇸' },
    { name: 'Spanish', code: 'ES', flag: '🇪🇸' },
    { name: 'French', code: 'FR', flag: '🇫🇷' },
    { name: 'German', code: 'DE', flag: '🇩🇪' },
    { name: 'Arabic', code: 'AR', flag: '🇦🇪' },
  ];

  const handleLanguageChange = (lang: string) => {
    setCurrentLanguage(lang);
    setIsLanguageOpen(false);
    toast.success(`Language changed to ${lang}`);
  };

  const handleLogout = async () => {
    try {
      logout();
      toast.success('Logged out successfully');
      navigate('/login');
    } catch (error) {
      toast.error('Failed to log out');
      console.error(error);
    }
  };

  const toggleTheme = () => {
    const newDark = !isDark;
    setIsDark(newDark);
    if (newDark) {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
    toast.success(`${newDark ? 'Dark' : 'Light'} mode enabled`);
  };

  return (
    <header className="sticky top-0 z-30 flex h-16 w-full items-center justify-between border-b border-border bg-card/80 px-4 backdrop-blur-md">
      {/* Left section - Empty to help centering */}
      <div className="flex-1 hidden md:flex" />

      {/* Center section - Quick Create & Search */}
      <div className="flex-[2] flex items-center justify-center gap-4 overflow-hidden">
        {isLogged && (
          <div className="flex items-center gap-4 w-full max-w-2xl justify-center">
            {/* Quick Create Button */}
            <button 
              onClick={onOpenQuickCreate}
              className="flex h-10 items-center gap-2 rounded-full bg-primary px-5 text-sm font-bold text-primary-foreground transition-all hover:bg-primary/90 active:scale-95 shrink-0 shadow-md shadow-primary/20"
            >
              <Plus size={18} />
              <span className="hidden lg:inline uppercase tracking-widest text-[10px]">Quick Create</span>
            </button>

            {/* Search Bar */}
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
              <input
                type="text"
                placeholder="Search anything..."
                className="h-10 w-full rounded-full border border-border bg-background/50 pl-11 pr-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-background transition-all"
                onKeyDown={(e) => e.key === 'Enter' && toast.info(`Searching for: ${e.currentTarget.value}`)}
              />
            </div>
          </div>
        )}
      </div>

      {/* Right section - Icons & Profile */}
      <div className="flex-1 flex items-center justify-end gap-2">
        <div className="h-6 w-px bg-border mx-2" />

        <div className="relative">
          <button 
            onClick={() => setIsLanguageOpen(!isLanguageOpen)}
            className={cn(
              "rounded-full p-2 hover:bg-accent text-muted-foreground transition-all flex items-center gap-1.5",
              isLanguageOpen && "bg-accent text-primary"
            )}
          >
            <Globe size={20} />
            <span className="text-[10px] font-bold uppercase">{languages.find(l => l.name === currentLanguage)?.code}</span>
          </button>

          <AnimatePresence>
            {isLanguageOpen && (
              <>
                <div 
                  className="fixed inset-0 z-10" 
                  onClick={() => setIsLanguageOpen(false)} 
                />
                <motion.div
                  initial={{ opacity: 0, y: 10, scale: 0.95 }}
                  animate={{ opacity: 1, y: 0, scale: 1 }}
                  exit={{ opacity: 0, y: 10, scale: 0.95 }}
                  className="absolute right-0 mt-2 w-48 origin-top-right rounded-xl border border-border bg-card p-2 shadow-xl z-20"
                >
                  <div className="px-3 py-2 mb-1 border-b border-border">
                    <p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">Select Language</p>
                  </div>
                  {languages.map((lang) => (
                    <button 
                      key={lang.code}
                      onClick={() => handleLanguageChange(lang.name)}
                      className={cn(
                        "flex w-full items-center justify-between rounded-lg px-3 py-2 text-sm font-medium transition-all hover:bg-accent",
                        currentLanguage === lang.name ? "text-primary bg-primary/5" : "text-muted-foreground"
                      )}
                    >
                      <div className="flex items-center gap-3">
                        <span>{lang.flag}</span>
                        <span>{lang.name}</span>
                      </div>
                      {currentLanguage === lang.name && (
                        <div className="h-1.5 w-1.5 rounded-full bg-primary" />
                      )}
                    </button>
                  ))}
                </motion.div>
              </>
            )}
          </AnimatePresence>
        </div>

        <button 
          onClick={toggleTheme}
          className="rounded-full p-2 hover:bg-accent text-muted-foreground transition-colors"
        >
          {isDark ? <Sun size={20} /> : <Moon size={20} />}
        </button>

        {isLogged && (
          <div className="relative">
            <button 
              onClick={() => setIsNotificationsOpen(!isNotificationsOpen)}
              className={cn(
                "relative rounded-full p-2 hover:bg-accent text-muted-foreground transition-all",
                isNotificationsOpen && "bg-accent text-primary"
              )}
            >
              <Bell size={20} />
              {unreadCount > 0 && (
                <span className="absolute right-2 top-2 h-2 w-2 rounded-full bg-destructive border-2 border-card" />
              )}
            </button>

            <AnimatePresence>
              {isNotificationsOpen && (
                <>
                  <div 
                    className="fixed inset-0 z-10" 
                    onClick={() => setIsNotificationsOpen(false)} 
                  />
                  <motion.div
                    initial={{ opacity: 0, y: 10, scale: 0.95 }}
                    animate={{ opacity: 1, y: 0, scale: 1 }}
                    exit={{ opacity: 0, y: 10, scale: 0.95 }}
                    className="absolute right-0 mt-2 w-80 origin-top-right rounded-xl border border-border bg-card p-2 shadow-xl z-20"
                  >
                    <div className="flex items-center justify-between px-3 py-2 mb-1 border-b border-border">
                      <p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">Notifications</p>
                      {liveNotifications.length > 0 && (
                        <button 
                          onClick={clearNotifications}
                          className="text-[10px] font-bold uppercase text-primary hover:underline"
                        >
                          Mark all as read
                        </button>
                      )}
                    </div>
                    <div className="max-h-[300px] overflow-y-auto">
                      {liveNotifications.length > 0 ? liveNotifications.map((n) => (
                        <button 
                          key={n.id}
                          onClick={() => {
                            markAsRead(n.id);
                            navigate(n.link);
                            setIsNotificationsOpen(false);
                            toast.info(`Viewing: ${n.title}`);
                          }}
                          className={cn(
                            "flex w-full items-start gap-3 rounded-lg px-3 py-3 text-left transition-all hover:bg-accent",
                            !n.read && "bg-primary/5"
                          )}
                        >
                          <div className={cn(
                            "mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full",
                            n.type === 'project' ? "bg-blue-500/10 text-blue-500" :
                            n.type === 'task' ? "bg-purple-500/10 text-purple-500" :
                            n.type === 'finance' ? "bg-green-500/10 text-green-500" :
                            n.type === 'crm' ? "bg-orange-500/10 text-orange-500" :
                            "bg-slate-500/10 text-slate-500"
                          )}>
                            {n.type === 'project' ? <Briefcase size={14} /> :
                             n.type === 'task' ? <CheckSquare size={14} /> :
                             n.type === 'finance' ? <DollarSign size={14} /> :
                             n.type === 'crm' ? <Users size={14} /> :
                             <Zap size={14} />}
                          </div>
                          <div className="flex flex-col min-w-0">
                            <div className="flex items-center justify-between gap-2">
                              <span className={cn("text-xs font-bold truncate", !n.read ? "text-foreground" : "text-muted-foreground")}>
                                {n.title}
                              </span>
                              <span className="text-[10px] text-muted-foreground whitespace-nowrap">{n.time}</span>
                            </div>
                            <p className="text-[10px] text-muted-foreground line-clamp-2 mt-0.5">
                              {n.description}
                            </p>
                          </div>
                          {!n.read && (
                            <div className="mt-2 h-1.5 w-1.5 shrink-0 rounded-full bg-primary" />
                          )}
                        </button>
                      )) : (
                        <div className="py-8 text-center">
                          <Bell size={24} className="mx-auto text-muted-foreground/30 mb-2" />
                          <p className="text-xs text-muted-foreground">No new notifications</p>
                        </div>
                      )}
                    </div>
                    {liveNotifications.length > 0 && (
                      <div className="mt-1 border-t border-border pt-1">
                        <button 
                          onClick={() => {
                            navigate('/');
                            setIsNotificationsOpen(false);
                            toast.info('Viewing all recent activity on Dashboard');
                          }}
                          className="flex w-full items-center justify-center py-2 text-[10px] font-bold uppercase tracking-wider text-muted-foreground hover:text-primary transition-colors"
                        >
                          View All Activity
                        </button>
                      </div>
                    )}
                  </motion.div>
                </>
              )}
            </AnimatePresence>
          </div>
        )}

        <div className="h-6 w-px bg-border mx-2" />

        <div className="relative">
          <button 
            onClick={() => setIsProfileOpen(!isProfileOpen)}
            className="flex items-center gap-2 rounded-full p-1 pl-2 hover:bg-accent transition-colors"
          >
            <div className="hidden text-right sm:block">
              <p className="text-sm font-semibold leading-none">{profile?.name || 'User'}</p>
              <p className="text-[10px] text-muted-foreground font-medium uppercase tracking-wider">{profile?.role || 'Member'}</p>
            </div>
            {profile?.photoURL ? (
              <img src={profile.photoURL} alt={profile.name} className="h-8 w-8 rounded-full object-cover" referrerPolicy="no-referrer" />
            ) : (
              <div className="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                <User size={20} />
              </div>
            )}
          </button>

          <AnimatePresence>
            {isProfileOpen && (
              <>
                <div 
                  className="fixed inset-0 z-10" 
                  onClick={() => setIsProfileOpen(false)} 
                />
                <motion.div
                  initial={{ opacity: 0, y: 10, scale: 0.95 }}
                  animate={{ opacity: 1, y: 0, scale: 1 }}
                  exit={{ opacity: 0, y: 10, scale: 0.95 }}
                  className="absolute right-0 mt-2 w-56 origin-top-right rounded-xl border border-border bg-card p-2 shadow-xl z-20"
                >
                  <div className="px-3 py-2 mb-2 border-b border-border">
                    <p className="text-sm font-bold">{profile?.name || 'User'}</p>
                    <p className="text-xs text-muted-foreground">{profile?.email || ''}</p>
                  </div>
                  <button 
                    onClick={() => {
                      navigate('/profile');
                      setIsProfileOpen(false);
                    }}
                    className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-accent-foreground transition-all"
                  >
                    <User size={18} />
                    Profile Settings
                  </button>
                  {hasPermission('settings.view') && (
                    <button 
                      onClick={() => {
                        navigate('/settings');
                        setIsProfileOpen(false);
                      }}
                      className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-accent-foreground transition-all"
                    >
                      <Settings size={18} />
                      System Settings
                    </button>
                  )}
                  {hasPermission('dashboard.view') && (
                    <button 
                      onClick={() => {
                        toast.info('Opening activity logs...');
                        setIsProfileOpen(false);
                      }}
                      className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-accent-foreground transition-all"
                    >
                      <History size={18} />
                      Activity Logs
                    </button>
                  )}
                  <div className="my-1 border-t border-border" />
                  <button 
                    onClick={() => {
                      handleLogout();
                      setIsProfileOpen(false);
                    }}
                    className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-destructive hover:bg-destructive/10 transition-all"
                  >
                    <LogOut size={18} />
                    Logout
                  </button>
                </motion.div>
              </>
            )}
          </AnimatePresence>
        </div>
      </div>
    </header>
  );
}
