'use client';

import { useState, useRef, useEffect } from 'react';
import { Bell, Search, ChevronRight, HelpCircle, Activity, Loader2, X, FolderKanban } from 'lucide-react';
import { useSession } from '../lib/session-context';
import { api } from '../lib/api';
import type { Project } from '../data/projectsData';

interface TopBarProps {
  breadcrumbs: { label: string; onClick?: () => void }[];
  onNavigate: (section: string, newProjectId?: string, options?: { settingsTab?: string }) => void;
  /** True when loaded projects include at least one activity entry (bell badge). */
  activityHighlight?: boolean;
  projects?: Project[];
}

type ActivityFeedItem = {
  id: string;
  projectId: string;
  projectName: string;
  action: string;
  detail?: string;
  user?: string;
  timestamp: string;
};

function formatRelativeTime(iso: string): string {
  const t = new Date(iso).getTime();
  if (Number.isNaN(t)) return '';
  const diffMs = Date.now() - t;
  const mins = Math.floor(diffMs / 60000);
  if (mins < 1) return 'Just now';
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  if (days < 7) return `${days}d ago`;
  return new Date(iso).toLocaleDateString();
}

export default function TopBar({ breadcrumbs, onNavigate, activityHighlight = false, projects = [] }: TopBarProps) {
  const { user: sessionUser } = useSession();
  const userInitials = sessionUser?.name ? sessionUser.name.split(' ').map(w => w[0]).join('').toUpperCase().slice(0, 2) : '?';
  const [notificationsOpen, setNotificationsOpen] = useState(false);
  const notificationsRef = useRef<HTMLDivElement>(null);
  const [feedItems, setFeedItems] = useState<ActivityFeedItem[]>([]);
  const [feedLoading, setFeedLoading] = useState(false);
  const [feedError, setFeedError] = useState<string | null>(null);

  // Search state
  const [searchQuery, setSearchQuery] = useState('');
  const [searchOpen, setSearchOpen] = useState(false);
  const searchRef = useRef<HTMLDivElement>(null);

  const filteredProjects = projects.filter(p =>
    p.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    p.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
    p.tags.some(t => t.toLowerCase().includes(searchQuery.toLowerCase()))
  ).slice(0, 5);

  useEffect(() => {
    if (!searchOpen) return;
    const close = (e: MouseEvent) => {
      if (searchRef.current && !searchRef.current.contains(e.target as Node)) {
        setSearchOpen(false);
      }
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [searchOpen]);

  useEffect(() => {
    if (!notificationsOpen) return;
    const close = (e: MouseEvent) => {
      if (notificationsRef.current && !notificationsRef.current.contains(e.target as Node)) {
        setNotificationsOpen(false);
      }
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [notificationsOpen]);

  useEffect(() => {
    if (!notificationsOpen) return;
    let cancelled = false;

    const load = async () => {
      if (!cancelled) {
        setFeedLoading(true);
        setFeedError(null);
      }
      try {
        const data = await api.getActivityNotifications(40);
        if (!cancelled) {
          setFeedItems(data.items);
          setFeedLoading(false);
        }
      } catch {
        if (!cancelled) {
          setFeedError('Could not load activity');
          setFeedLoading(false);
        }
      }
    };

    load();
    return () => {
      cancelled = true;
    };
  }, [notificationsOpen]);

  return (
    <header className="h-14 glass border-b border-border flex items-center justify-between px-6 sticky top-0 z-40">
      <nav className="flex items-center gap-1.5 text-sm">
        {breadcrumbs.map((b, i) => (
          <span key={i} className="flex items-center gap-1.5">
            {i > 0 && <ChevronRight className="w-3.5 h-3.5 text-muted" />}
            {b.onClick ? (
              <button onClick={b.onClick} className="text-muted hover:text-foreground transition-colors cursor-pointer">
                {b.label}
              </button>
            ) : (
              <span className="text-foreground font-medium">{b.label}</span>
            )}
          </span>
        ))}
      </nav>

      <div className="flex items-center gap-3">
        <div ref={searchRef} className="relative">
          <div className="flex items-center gap-2 glass-light rounded-lg px-3 py-1.5">
            <Search className="w-3.5 h-3.5 text-muted" />
            <input
              type="text"
              placeholder="Search conversions..."
              value={searchQuery}
              onChange={(e) => { setSearchQuery(e.target.value); setSearchOpen(true); }}
              onFocus={() => setSearchOpen(true)}
              className="bg-transparent text-xs text-foreground outline-none placeholder-muted w-48"
            />
            {searchQuery ? (
              <button onClick={() => { setSearchQuery(''); setSearchOpen(false); }} className="text-muted hover:text-foreground">
                <X className="w-3 h-3" />
              </button>
            ) : (
              <kbd className="text-[9px] text-muted bg-surface rounded px-1.5 py-0.5 font-mono border border-border">⌘K</kbd>
            )}
          </div>
          {searchOpen && searchQuery && (
            <div className="absolute left-0 top-full z-50 mt-1.5 w-80 rounded-xl border border-border bg-surface/95 shadow-lg backdrop-blur-md py-2">
              {filteredProjects.length === 0 ? (
                <div className="px-3 py-4 text-center text-xs text-muted">No conversions found</div>
              ) : (
                <ul>
                  {filteredProjects.map((p) => (
                    <li key={p.id} className="border-b border-border/60 last:border-0">
                      <button
                        type="button"
                        className="w-full px-3 py-2.5 text-left hover:bg-surface-light/80 transition-colors cursor-pointer flex items-center gap-2.5"
                        onClick={() => {
                          setSearchOpen(false);
                          setSearchQuery('');
                          onNavigate('conversion-dashboard', p.id);
                        }}
                      >
                        <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-accent/10 text-accent">
                          <FolderKanban className="w-3.5 h-3.5" />
                        </div>
                        <div className="min-w-0">
                          <p className="text-xs font-medium text-foreground truncate">{p.name}</p>
                          <p className="text-[10px] text-muted truncate">{p.status}</p>
                        </div>
                      </button>
                    </li>
                  ))}
                </ul>
              )}
            </div>
          )}
        </div>

        <div className="relative" ref={notificationsRef}>
          <button
            type="button"
            aria-expanded={notificationsOpen}
            aria-haspopup="true"
            aria-label="Notifications"
            onClick={() => setNotificationsOpen((o) => !o)}
            className="relative p-2 rounded-lg hover:bg-surface-light transition-colors cursor-pointer"
          >
            <Bell className="w-4 h-4 text-muted" />
            {activityHighlight ? (
              <span className="absolute top-1.5 right-1.5 w-2 h-2 bg-accent rounded-full" aria-hidden />
            ) : null}
          </button>
          {notificationsOpen && (
            <div
              className="absolute right-0 top-full z-50 mt-1.5 w-[min(100vw-2rem,22rem)] rounded-xl border border-border bg-surface/95 shadow-lg backdrop-blur-md py-2"
              role="menu"
            >
              <div className="px-3 pb-2 border-b border-border">
                <p className="text-xs font-semibold text-foreground">Notifications</p>
                <p className="text-[10px] text-muted mt-0.5">Recent activity from your conversions</p>
              </div>
              <ul className="max-h-72 overflow-y-auto py-1">
                {feedLoading && (
                  <li className="flex items-center justify-center gap-2 py-8 text-muted">
                    <Loader2 className="w-4 h-4 animate-spin" />
                    <span className="text-xs">Loading…</span>
                  </li>
                )}
                {!feedLoading && feedError && (
                  <li className="px-3 py-4 text-center text-xs text-danger">{feedError}</li>
                )}
                {!feedLoading && !feedError && feedItems.length === 0 && (
                  <li className="px-3 py-6 text-center text-xs text-muted">No conversion activity yet.</li>
                )}
                {!feedLoading &&
                  !feedError &&
                  feedItems.map((item) => (
                    <li key={item.id} className="border-b border-border/60 last:border-0">
                      <button
                        type="button"
                        role="menuitem"
                        className="w-full px-3 py-2.5 text-left hover:bg-surface-light/80 transition-colors cursor-pointer"
                        onClick={() => {
                          setNotificationsOpen(false);
                          onNavigate('conversion-dashboard', item.projectId);
                        }}
                      >
                        <div className="flex gap-2.5">
                          <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-accent/10 text-accent">
                            <Activity className="w-4 h-4" />
                          </div>
                          <div className="min-w-0">
                            <p className="text-xs font-medium text-foreground leading-snug">{item.action}</p>
                            <p className="text-[11px] text-muted mt-0.5 leading-relaxed truncate">{item.projectName}</p>
                            {item.detail ? (
                              <p className="text-[11px] text-muted/90 mt-0.5 leading-relaxed line-clamp-2">{item.detail}</p>
                            ) : null}
                            <p className="text-[10px] text-muted/70 mt-1">
                              {formatRelativeTime(item.timestamp)}
                              {item.user ? ` · ${item.user}` : ''}
                            </p>
                          </div>
                        </div>
                      </button>
                    </li>
                  ))}
              </ul>
              <div className="border-t border-border px-2 pt-1 pb-1">
                <button
                  type="button"
                  role="menuitem"
                  className="w-full rounded-lg px-2 py-2 text-left text-xs font-medium text-accent hover:bg-surface-light transition-colors cursor-pointer"
                  onClick={() => {
                    setNotificationsOpen(false);
                    onNavigate('settings', undefined, { settingsTab: 'notifications' });
                  }}
                >
                  Notification preferences…
                </button>
              </div>
            </div>
          )}
        </div>

        <button className="p-2 rounded-lg hover:bg-surface-light transition-colors cursor-pointer">
          <HelpCircle className="w-4 h-4 text-muted" />
        </button>

        <div className="flex items-center gap-2.5 ml-1 pl-3 border-l border-border">
          <button
            onClick={() => onNavigate('settings')}
            className="flex items-center gap-2.5 hover:bg-surface-light rounded-lg p-1 -m-1 transition-colors cursor-pointer"
            title="Settings"
          >
            <div className="w-8 h-8 rounded-full gradient-accent flex items-center justify-center text-white text-xs font-bold">
              {userInitials}
            </div>
            <div className="hidden xl:block text-left">
              <p className="text-xs font-medium text-foreground leading-tight">{sessionUser?.name || 'User'}</p>
              <p className="text-[10px] text-muted leading-tight">{sessionUser?.email || ''}</p>
            </div>
          </button>
        </div>
      </div>
    </header>
  );
}
