import { ref } from "vue"
import { kappa } from "@/services/kappa-api"
import type {
  KappaInitiative,
  KappaUserStory,
  KappaLogbookEntry,
  KappaPlanningEntry,
  KappaBusinessRule,
  KappaRequirement,
} from "@/types/kappa"

export interface SearchResult {
  type: "initiative" | "userstory" | "logbook" | "planning" | "businessrule" | "requirement"
  id: number
  title: string
  description?: string
  projectId?: number
  projectName?: string
}

export function useSearch() {
  const results = ref<SearchResult[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  async function search(query: string) {
    if (!query.trim()) {
      results.value = []
      return
    }

    loading.value = true
    error.value = null

    try {
      const allResults: SearchResult[] = []

      const initiativeResult = await Promise.allSettled([kappa.getInitiatives()])
      if (initiativeResult[0].status === "fulfilled") {
        const data = initiativeResult[0].value as KappaInitiative[]
        const items = Array.isArray(data) ? data : (data as { results?: KappaInitiative[] }).results ?? []
        items.forEach((item: KappaInitiative) => {
          if (matchesQuery(item.name || item.initiative_name || "", query) ||
              matchesQuery(item.key || "", query) ||
              matchesQuery(item.description || "", query)) {
            allResults.push({
              type: "initiative",
              id: item.id,
              title: item.name || item.initiative_name || `Project ${item.id}`,
              description: item.description,
              projectId: item.id,
              projectName: item.name || item.initiative_name,
            })
          }
        })
      }

      const storyResult = await Promise.allSettled([kappa.getUserStories(undefined, 1, 50)])
      if (storyResult[0].status === "fulfilled") {
        const resp = storyResult[0].value
        const items = resp.results
        items.forEach((item: KappaUserStory) => {
          if (matchesQuery(item.title, query) ||
              matchesQuery(item.code || "", query) ||
              matchesQuery(item.description || "", query)) {
            allResults.push({
              type: "userstory",
              id: item.id || Math.random(),
              title: item.title,
              description: item.description,
              projectId: typeof item.initiative === "number" ? item.initiative : undefined,
            })
          }
        })
      }

      const logResult = await Promise.allSettled([kappa.getLogbooks()])
      if (logResult[0].status === "fulfilled") {
        const data = logResult[0].value as KappaLogbookEntry[]
        const items = Array.isArray(data) ? data : (data as { results?: KappaLogbookEntry[] }).results ?? []
        items.forEach((item: KappaLogbookEntry) => {
          if (matchesQuery(item.description, query)) {
            allResults.push({
              type: "logbook",
              id: item.id || Math.random(),
              title: item.description.slice(0, 80),
              description: item.description,
              projectId: typeof item.initiative === "number" ? item.initiative : undefined,
            })
          }
        })
      }

      const planResult = await Promise.allSettled([kappa.getPlannings()])
      if (planResult[0].status === "fulfilled") {
        const data = planResult[0].value as KappaPlanningEntry[]
        const items = Array.isArray(data) ? data : (data as { results?: KappaPlanningEntry[] }).results ?? []
        items.forEach((item: KappaPlanningEntry) => {
          if (matchesQuery(item.description, query) ||
              matchesQuery(item.responsible || "", query)) {
            allResults.push({
              type: "planning",
              id: item.id || Math.random(),
              title: item.description.slice(0, 80),
              description: item.description,
              projectId: typeof item.initiative === "number" ? item.initiative : undefined,
            })
          }
        })
      }

      const ruleResult = await Promise.allSettled([kappa.getBusinessRules()])
      if (ruleResult[0].status === "fulfilled") {
        const data = ruleResult[0].value as KappaBusinessRule[]
        const items = Array.isArray(data) ? data : (data as { results?: KappaBusinessRule[] }).results ?? []
        items.forEach((item: KappaBusinessRule) => {
          if (matchesQuery(item.name, query) ||
              matchesQuery(item.description, query)) {
            allResults.push({
              type: "businessrule",
              id: Math.random(),
              title: item.name,
              description: item.description,
              projectId: typeof item.initiative === "number" ? item.initiative : undefined,
            })
          }
        })
      }

      const reqResult = await Promise.allSettled([kappa.getRequirements()])
      if (reqResult[0].status === "fulfilled") {
        const data = reqResult[0].value as KappaRequirement[]
        const items = Array.isArray(data) ? data : (data as { results?: KappaRequirement[] }).results ?? []
        items.forEach((item: KappaRequirement) => {
          if (matchesQuery(item.name || item.name_requirement || "", query) ||
              matchesQuery(item.description, query)) {
            allResults.push({
              type: "requirement",
              id: Math.random(),
              title: item.name || item.name_requirement || "Requirement",
              description: item.description,
              projectId: typeof item.initiative === "number" ? item.initiative : undefined,
            })
          }
        })
      }

      results.value = allResults
    } catch (e: any) {
      error.value = e.message
      results.value = []
    } finally {
      loading.value = false
    }
  }

  function matchesQuery(text: string, query: string): boolean {
    return text.toLowerCase().includes(query.toLowerCase())
  }

  function clearResults() {
    results.value = []
  }

  return {
    results,
    loading,
    error,
    search,
    clearResults,
  }
}

export const typeColors: Record<SearchResult["type"], { bg: string; text: string; label: string }> = {
  initiative: { bg: "bg-blue-100 dark:bg-blue-900", text: "text-blue-700 dark:text-blue-300", label: "Project" },
  userstory: { bg: "bg-green-100 dark:bg-green-900", text: "text-green-700 dark:text-green-300", label: "User Story" },
  logbook: { bg: "bg-purple-100 dark:bg-purple-900", text: "text-purple-700 dark:text-purple-300", label: "Logbook" },
  planning: { bg: "bg-orange-100 dark:bg-orange-900", text: "text-orange-700 dark:text-orange-300", label: "Planning" },
  businessrule: { bg: "bg-red-100 dark:bg-red-900", text: "text-red-700 dark:text-red-300", label: "Rule" },
  requirement: { bg: "bg-yellow-100 dark:bg-yellow-900", text: "text-yellow-700 dark:text-yellow-300", label: "Req" },
}