"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import {
  BarChart3,
  Calendar,
  CheckSquare,
  FileText,
  Paperclip,
  FolderKanban,
  LayoutDashboard,
  Bell,
  BellRing,
  Settings,
  Bot,
  BrainCircuit,
  Cpu,
  Sparkles,
  Users2,
  Inbox,
  Building2,
  Shield,
  Webhook,
  PlugZap,
  Workflow,
  Bookmark,
  Wallet,
  MessageSquareText,
  Network,
} from "lucide-react";
import type { LucideIcon } from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { useWorkspaceStore } from "@/stores/workspace-store";

export interface GlobalSearchResult {
  id: string;
  title: string;
  subtitle: string;
  href: string;
  section:
    | "Quick Actions"
    | "Pages"
    | "Projects"
    | "Tasks"
    | "Notes"
    | "Documents"
    | "Saved Views"
    | "Calendar";
  icon: LucideIcon;
}

const PAGE_RESULTS: GlobalSearchResult[] = [
  {
    id: "page-dashboard",
    title: "Dashboard",
    subtitle: "Overview of your workspace",
    href: "/",
    section: "Pages",
    icon: LayoutDashboard,
  },
  {
    id: "page-command-center",
    title: "Command Center",
    subtitle: "Daily cockpit for tasks, reminders, focus, rewards, reflection, and project risk",
    href: "/command-center",
    section: "Pages",
    icon: Sparkles,
  },
  {
    id: "page-life-map",
    title: "Life Map",
    subtitle: "Momentum score, system radar, bottlenecks, and leverage moves",
    href: "/life-map",
    section: "Pages",
    icon: Network,
  },
  {
    id: "page-inbox",
    title: "Inbox",
    subtitle: "Unsorted tasks and notes",
    href: "/inbox",
    section: "Pages",
    icon: Inbox,
  },
  {
    id: "page-reminders",
    title: "Reminders",
    subtitle: "Future attention pings and snoozed context",
    href: "/reminders",
    section: "Pages",
    icon: BellRing,
  },
  {
    id: "page-tasks",
    title: "Tasks",
    subtitle: "All tasks and saved views",
    href: "/tasks",
    section: "Pages",
    icon: CheckSquare,
  },
  {
    id: "page-notes",
    title: "Notes",
    subtitle: "Your notes and folders",
    href: "/notes",
    section: "Pages",
    icon: FileText,
  },
  {
    id: "page-vault",
    title: "Vault Center",
    subtitle: "Scan, sort, inspect, and act on important documents",
    href: "/vault",
    section: "Pages",
    icon: Shield,
  },
  {
    id: "page-projects",
    title: "Projects",
    subtitle: "Active projects and workspaces",
    href: "/projects",
    section: "Pages",
    icon: FolderKanban,
  },
  {
    id: "page-calendar",
    title: "Calendar",
    subtitle: "Events, deadlines, and scheduling",
    href: "/calendar",
    section: "Pages",
    icon: Calendar,
  },
  {
    id: "page-teams",
    title: "Teams",
    subtitle: "Members, invites, and permissions",
    href: "/teams",
    section: "Pages",
    icon: Users2,
  },
  {
    id: "page-chat",
    title: "Chat",
    subtitle: "Work chat, team channels, and operational conversations",
    href: "/chat",
    section: "Pages",
    icon: MessageSquareText,
  },
  {
    id: "page-organizations",
    title: "Organizations",
    subtitle: "Billing, seats, and security",
    href: "/organizations",
    section: "Pages",
    icon: Building2,
  },
  {
    id: "page-admin",
    title: "Admin",
    subtitle: "Workspace operations and oversight",
    href: "/admin",
    section: "Pages",
    icon: Shield,
  },
  {
    id: "page-integrations",
    title: "Integrations",
    subtitle: "Slack alerts and calendar subscriptions",
    href: "/integrations",
    section: "Pages",
    icon: PlugZap,
  },
  {
    id: "page-automations",
    title: "Automations",
    subtitle: "Rules, filters, and action runs",
    href: "/automations",
    section: "Pages",
    icon: Workflow,
  },
  {
    id: "page-developers",
    title: "Developers",
    subtitle: "API tokens, webhooks, and delivery logs",
    href: "/developers",
    section: "Pages",
    icon: Webhook,
  },
  {
    id: "page-ai",
    title: "AI Assistant",
    subtitle: "Mindavio AI workspace assistant",
    href: "/ai",
    section: "Pages",
    icon: Bot,
  },
  {
    id: "page-notifications",
    title: "Notifications",
    subtitle: "Mentions, invites, and alerts",
    href: "/notifications",
    section: "Pages",
    icon: Bell,
  },
  {
    id: "page-mindset",
    title: "Mindset",
    subtitle: "Goals, affirmations, and personal direction",
    href: "/mindset",
    section: "Pages",
    icon: Sparkles,
  },
  {
    id: "page-finances",
    title: "Finances",
    subtitle: "Income, expenses, budgets, and recurring payments",
    href: "/finances",
    section: "Pages",
    icon: Wallet,
  },
  {
    id: "page-insights",
    title: "Insights",
    subtitle: "CRM, KPIs, goals, and business intelligence",
    href: "/insights",
    section: "Pages",
    icon: BarChart3,
  },
  {
    id: "page-settings",
    title: "Settings",
    subtitle: "Workspace and account configuration",
    href: "/settings",
    section: "Pages",
    icon: Settings,
  },
];

const QUICK_ACTION_RESULTS: GlobalSearchResult[] = [
  {
    id: "quick-ai-next-move",
    title: "Ask AI for next move",
    subtitle: "Operating Coach analyzes tasks, projects, reminders, events, and risks",
    href: "/ai?prompt=Agiere%20als%20mein%20Operating%20Coach.%20Analysiere%20meine%20Aufgaben%2C%20Projekte%2C%20Termine%2C%20Reminders%2C%20Achievements%20und%20Risiken.%20Gib%20mir%20genau%20den%20n%C3%A4chsten%20besten%20Move%20f%C3%BCr%20jetzt%3A%201%20klare%20Aktion%2C%20warum%20sie%20jetzt%20z%C3%A4hlt%2C%20welche%20Daten%20dich%20darauf%20bringen%2C%20und%20die%20ersten%203%20Schritte.",
    section: "Quick Actions",
    icon: Cpu,
  },
  {
    id: "quick-ai-bottleneck",
    title: "Run bottleneck scan",
    subtitle: "Find the one workspace constraint costing the most momentum",
    href: "/ai?prompt=Mach%20einen%20Bottleneck%20Scan%20f%C3%BCr%20meinen%20Workspace.%20Finde%20den%20einen%20Engpass%2C%20der%20gerade%20am%20meisten%20Fortschritt%20blockiert.%20Zeige%20Symptome%2C%20betroffene%20Projekte%2FTasks%2C%20Risiko%2C%20und%20einen%20pragmatischen%20Fix%20f%C3%BCr%20die%20n%C3%A4chsten%2024%20Stunden.",
    section: "Quick Actions",
    icon: BrainCircuit,
  },
  {
    id: "quick-create-task",
    title: "Create task",
    subtitle: "Open the new task form",
    href: "/tasks?create=1",
    section: "Quick Actions",
    icon: CheckSquare,
  },
  {
    id: "quick-create-note",
    title: "Create note",
    subtitle: "Create and open a fresh note",
    href: "/notes?create=1",
    section: "Quick Actions",
    icon: FileText,
  },
  {
    id: "quick-create-project",
    title: "Create project",
    subtitle: "Open the new project form",
    href: "/projects?create=1",
    section: "Quick Actions",
    icon: FolderKanban,
  },
  {
    id: "quick-create-event",
    title: "Create event",
    subtitle: "Open the new calendar event form",
    href: "/calendar?create=1",
    section: "Quick Actions",
    icon: Calendar,
  },
  {
    id: "quick-create-reminder",
    title: "Create reminder",
    subtitle: "Schedule a future attention ping",
    href: "/reminders?create=1",
    section: "Quick Actions",
    icon: BellRing,
  },
  {
    id: "quick-create-team",
    title: "Create team",
    subtitle: "Open the team creation modal",
    href: "/teams?create=1",
    section: "Quick Actions",
    icon: Users2,
  },
];

function rankTextMatch(query: string, ...values: string[]) {
  const normalizedQuery = query.toLowerCase();
  const queryTerms = normalizedQuery.split(/\s+/).filter(Boolean);
  let bestScore = 0;

  for (const value of values) {
    const normalizedValue = value.toLowerCase();

    if (!normalizedValue) continue;

    if (normalizedValue === normalizedQuery) {
      bestScore = Math.max(bestScore, 120);
      continue;
    }

    if (normalizedValue.startsWith(normalizedQuery)) {
      bestScore = Math.max(bestScore, 100);
    } else if (normalizedValue.split(/\s+/).some((part) => part.startsWith(normalizedQuery))) {
      bestScore = Math.max(bestScore, 85);
    } else if (normalizedValue.includes(normalizedQuery)) {
      bestScore = Math.max(bestScore, 70);
    }

    if (queryTerms.length > 1) {
      const matchedTerms = queryTerms.filter((term) => normalizedValue.includes(term)).length;

      if (matchedTerms === queryTerms.length) {
        bestScore = Math.max(bestScore, 90 + matchedTerms * 2);
      } else if (matchedTerms > 0) {
        bestScore = Math.max(bestScore, 52 + matchedTerms * 4);
      }
    }
  }

  return bestScore;
}

export function useGlobalSearch(query: string) {
  const [results, setResults] = useState<GlobalSearchResult[]>([]);
  const [searching, setSearching] = useState(false);
  const supabase = createClient();
  const activeTeamId = useWorkspaceStore((state) => state.activeTeamId);
  const quickActions = useMemo(() => {
    const normalized = query.trim().toLowerCase();
    if (!normalized) return [];

    const actionIntent =
      normalized.startsWith("new") ||
      normalized.startsWith("create") ||
      normalized.startsWith("add") ||
      normalized.includes("next move") ||
      normalized.includes("operating coach") ||
      normalized.includes("bottleneck") ||
      normalized.includes("sprint") ||
      normalized.includes(" new ") ||
      normalized.includes(" create ") ||
      normalized.includes(" add ");

    if (!actionIntent) return [];

    return QUICK_ACTION_RESULTS.map((item, index) => ({
      item,
      index,
      score: rankTextMatch(normalized, item.title, item.subtitle),
    }))
      .filter((entry) => entry.score > 0)
      .sort((a, b) => b.score - a.score || a.index - b.index)
      .map((entry) => entry.item);
  }, [query]);

  const pageResults = useMemo(() => {
    const normalized = query.trim().toLowerCase();
    if (!normalized) return PAGE_RESULTS;

    return PAGE_RESULTS.map((item, index) => ({
      item,
      index,
      score: rankTextMatch(normalized, item.title, item.subtitle),
    }))
      .filter((entry) => entry.score > 0)
      .sort((a, b) => b.score - a.score || a.index - b.index)
      .map((entry) => entry.item);
  }, [query]);

  const searchData = useCallback(
    async (nextQuery: string) => {
      const normalized = nextQuery.trim();
      if (normalized.length < 2) {
        setResults([]);
        return;
      }

      setSearching(true);

      let tasksQuery = supabase
        .from("tasks")
        .select("id, title, description, deadline")
        .or(`title.ilike.%${normalized}%,description.ilike.%${normalized}%`)
        .is("parent_task_id", null)
        .limit(8);

      let notesQuery = supabase
        .from("notes")
        .select("id, title, updated_at")
        .ilike("title", `%${normalized}%`)
        .limit(8);

      let projectsQuery = supabase
        .from("projects")
        .select("id, name, description")
        .or(`name.ilike.%${normalized}%,description.ilike.%${normalized}%`)
        .limit(8);

      let eventsQuery = supabase
        .from("events")
        .select("id, title, description, start_time")
        .or(`title.ilike.%${normalized}%,description.ilike.%${normalized}%`)
        .limit(8);

      let documentsQuery = supabase
        .from("attachments")
        .select("id, entity_type, entity_id, file_name, created_at")
        .ilike("file_name", `%${normalized}%`)
        .limit(8);

      let savedViewsQuery = supabase
        .from("saved_views")
        .select("id, name, scope")
        .ilike("name", `%${normalized}%`)
        .limit(8);

      if (activeTeamId) {
        tasksQuery = tasksQuery.eq("team_id", activeTeamId);
        notesQuery = notesQuery.eq("team_id", activeTeamId);
        projectsQuery = projectsQuery.eq("team_id", activeTeamId);
        eventsQuery = eventsQuery.eq("team_id", activeTeamId);
        documentsQuery = documentsQuery.eq("team_id", activeTeamId);
        savedViewsQuery = savedViewsQuery.eq("team_id", activeTeamId);
      } else {
        tasksQuery = tasksQuery.is("team_id", null);
        notesQuery = notesQuery.is("team_id", null);
        projectsQuery = projectsQuery.is("team_id", null);
        eventsQuery = eventsQuery.is("team_id", null);
        documentsQuery = documentsQuery.is("team_id", null);
        savedViewsQuery = savedViewsQuery.is("team_id", null);
      }

      const [tasksRes, notesRes, projectsRes, eventsRes, documentsRes, savedViewsRes] =
        await Promise.all([
        tasksQuery,
        notesQuery,
        projectsQuery,
        eventsQuery,
        documentsQuery,
        savedViewsQuery,
      ]);

      const nextResults: GlobalSearchResult[] = [
        ...((projectsRes.data || [])
          .map((project) => ({
            id: `project-${project.id}`,
            title: project.name,
            subtitle: project.description || "Project",
            href: `/projects/${project.id}`,
            section: "Projects" as const,
            icon: FolderKanban,
            score: rankTextMatch(normalized, project.name, project.description || ""),
          }))
          .sort((a, b) => b.score - a.score) as Array<GlobalSearchResult & { score: number }>),
        ...((tasksRes.data || [])
          .map((task) => ({
            id: `task-${task.id}`,
            title: task.title,
            subtitle:
              task.description ||
              (task.deadline
                ? `Due ${new Date(task.deadline).toLocaleDateString()}`
                : "Task"),
            href: `/tasks?task=${task.id}`,
            section: "Tasks" as const,
            icon: CheckSquare,
            score: rankTextMatch(normalized, task.title, task.description || ""),
          }))
          .sort((a, b) => b.score - a.score) as Array<GlobalSearchResult & { score: number }>),
        ...((notesRes.data || [])
          .map((note) => ({
            id: `note-${note.id}`,
            title: note.title,
            subtitle: "Note",
            href: `/notes/${note.id}`,
            section: "Notes" as const,
            icon: FileText,
            score: rankTextMatch(normalized, note.title),
          }))
          .sort((a, b) => b.score - a.score) as Array<GlobalSearchResult & { score: number }>),
        ...((documentsRes.data || [])
          .map((document) => ({
            id: `document-${document.id}`,
            title: document.file_name,
            subtitle: `${document.entity_type} attachment`,
            href:
              document.entity_type === "note"
                ? `/notes/${document.entity_id}`
                : document.entity_type === "project"
                ? `/projects/${document.entity_id}`
                : `/tasks?task=${document.entity_id}`,
            section: "Documents" as const,
            icon: Paperclip,
            score: rankTextMatch(normalized, document.file_name),
          }))
          .sort((a, b) => b.score - a.score) as Array<GlobalSearchResult & { score: number }>),
        ...((savedViewsRes.data || [])
          .map((view) => ({
            id: `saved-view-${view.id}`,
            title: view.name,
            subtitle: `${view.scope} saved view`,
            href:
              view.scope === "tasks"
                ? `/tasks?savedView=${view.id}`
                : view.scope === "notes"
                ? `/notes?savedView=${view.id}`
                : view.scope === "documents"
                ? `/vault`
                : view.scope === "calendar"
                ? `/calendar?savedView=${view.id}`
                : `/projects?savedView=${view.id}`,
            section: "Saved Views" as const,
            icon: Bookmark,
            score: rankTextMatch(normalized, view.name, view.scope),
          }))
          .sort((a, b) => b.score - a.score) as Array<GlobalSearchResult & { score: number }>),
        ...((eventsRes.data || [])
          .map((event) => ({
            id: `event-${event.id}`,
            title: event.title,
            subtitle: event.description || new Date(event.start_time).toLocaleString(),
            href: `/calendar?event=${event.id}`,
            section: "Calendar" as const,
            icon: Calendar,
            score: rankTextMatch(normalized, event.title, event.description || ""),
          }))
          .sort((a, b) => b.score - a.score) as Array<GlobalSearchResult & { score: number }>),
      ].map((resultWithScore) => {
        const { score, ...result } = resultWithScore;
        void score;
        return result;
      });

      setResults(nextResults);
      setSearching(false);
    },
    [activeTeamId, supabase]
  );

  useEffect(() => {
    const handle = window.setTimeout(() => {
      void searchData(query);
    }, 180);

    return () => window.clearTimeout(handle);
  }, [query, searchData]);

  return {
    quickActions,
    pageResults,
    results,
    searching,
  };
}
