"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { useTaskStore, Task, TaskStatus } from "@/stores/useTaskStore"
import { Card, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { generateAvatarDataUrl } from "@/lib/avatar"
import { MessageSquare, Calendar, Paperclip } from "lucide-react"
import { format, isValid, parseISO } from "date-fns"

const typeColors: Record<string, string> = {
  idea: "bg-purple-500",
  task: "bg-blue-500",
  bug: "bg-red-500",
  research: "bg-green-500",
  plan: "bg-amber-500",
}

const typeLabels: Record<string, string> = {
  idea: "💡 Idea",
  task: "📋 Task",
  bug: "🐛 Bug",
  research: "🔬 Research",
  plan: "📐 Plan",
}

const priorityColors: Record<string, string> = {
  low: "text-slate-400",
  medium: "text-blue-400",
  high: "text-orange-400",
  urgent: "text-red-400",
}

const statusColors: Record<TaskStatus, string> = {
  open: "bg-slate-600",
  todo: "bg-slate-600",
  blocked: "bg-red-600",
  "in-progress": "bg-blue-600",
  review: "bg-yellow-600",
  validate: "bg-purple-600",
  archived: "bg-gray-600",
  canceled: "bg-red-800",
  done: "bg-green-600",
}

const formatStatusLabel = (status: TaskStatus) =>
  status === "todo"
    ? "To Do"
    : status
        .split("-")
        .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
        .join(" ")

function AvatarCircle({
  name,
  avatarUrl,
  seed,
  sizeClass = "h-6 w-6",
  title,
}: {
  name?: string
  avatarUrl?: string
  seed?: string
  sizeClass?: string
  title?: string
}) {
  const displayUrl = avatarUrl || generateAvatarDataUrl(seed || name || "default", name || "User")
  return (
    <img
      src={displayUrl}
      alt={name || "User avatar"}
      className={`${sizeClass} rounded-full border border-slate-700 object-cover bg-slate-800`}
      title={title || name || "User"}
    />
  )
}

interface AssignableUser {
  id: string
  name: string
  email?: string
  avatarUrl?: string
}

interface SearchViewProps {
  searchQuery: string
}

export function SearchView({ searchQuery }: SearchViewProps) {
  const router = useRouter()
  const { tasks, sprints } = useTaskStore()
  const [assignableUsers, setAssignableUsers] = useState<AssignableUser[]>([])

  useEffect(() => {
    let active = true
    const loadUsers = async () => {
      try {
        const response = await fetch("/api/auth/users", { cache: "no-store" })
        if (!response.ok) return
        const data = await response.json()
        if (!active || !Array.isArray(data?.users)) return
        setAssignableUsers(
          data.users.map((entry: { id: string; name: string; email?: string; avatarUrl?: string }) => ({
            id: entry.id,
            name: entry.name,
            email: entry.email,
            avatarUrl: entry.avatarUrl,
          }))
        )
      } catch {
        // Keep view usable if users lookup fails
      }
    }
    void loadUsers()
    return () => {
      active = false
    }
  }, [])

  const resolveAssignee = (assigneeId: string | undefined) => {
    if (!assigneeId) return null
    return assignableUsers.find((user) => user.id === assigneeId) || null
  }

  // Filter tasks by search query across ALL tasks
  const matchingTasks = tasks.filter((task) => {
    if (!searchQuery.trim()) return true
    const query = searchQuery.toLowerCase()
    const matchesTitle = task.title.toLowerCase().includes(query)
    const matchesDescription = task.description?.toLowerCase().includes(query) ?? false
    const matchesTags = task.tags?.some((tag) => tag.toLowerCase().includes(query)) ?? false
    const matchesAssignee = task.assigneeName?.toLowerCase().includes(query) ?? false
    const matchesStatus = formatStatusLabel(task.status).toLowerCase().includes(query)
    const matchesType = typeLabels[task.type]?.toLowerCase().includes(query) ?? false
    return matchesTitle || matchesDescription || matchesTags || matchesAssignee || matchesStatus || matchesType
  })

  // Sort by updatedAt descending (most recent first)
  const sortedTasks = matchingTasks.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())

  // Get sprint info for a task
  const getSprintInfo = (task: Task) => {
    if (!task.sprintId) return null
    const sprint = sprints.find((s) => s.id === task.sprintId)
    if (!sprint) return null
    return sprint
  }

  // Format date
  const formatDate = (dateStr: string) => {
    try {
      const date = parseISO(dateStr)
      if (!isValid(date)) return "Invalid date"
      return format(date, "MMM d, yyyy")
    } catch {
      return "Invalid date"
    }
  }

  if (!searchQuery.trim()) {
    return (
      <div className="flex flex-col items-center justify-center py-16 text-slate-400">
        <div className="w-16 h-16 mb-4 rounded-full bg-slate-800 flex items-center justify-center">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            className="h-8 w-8 text-slate-500"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
            />
          </svg>
        </div>
        <h3 className="text-lg font-medium text-slate-300 mb-2">Search Tasks</h3>
        <p className="text-sm text-slate-500 max-w-md text-center">
          Enter a search term above to find tasks across all projects, sprints, and statuses.
          <br />
          Search by title, description, tags, assignee, status, or type.
        </p>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {/* Search Results Header */}
      <div className="flex items-center justify-between">
        <p className="text-sm text-slate-400">
          Found <span className="text-white font-medium">{sortedTasks.length}</span> tasks matching &quot;
          <span className="text-blue-400">{searchQuery}</span>&quot;
        </p>
      </div>

      {/* Search Results List */}
      {sortedTasks.length === 0 ? (
        <div className="text-center py-12 text-slate-500">
          <p>No tasks found matching &quot;{searchQuery}&quot;</p>
          <p className="text-sm mt-2">Try a different search term</p>
        </div>
      ) : (
        <div className="space-y-3">
          {sortedTasks.map((task) => {
            const sprint = getSprintInfo(task)
            const assignee = resolveAssignee(task.assigneeId)
            const attachmentCount = task.attachments?.length || 0

            return (
              <Card
                key={task.id}
                className="bg-slate-900 border-slate-800 hover:border-slate-700 cursor-pointer transition-colors group"
                onClick={() => router.push(`/tasks/${encodeURIComponent(task.id)}`)}
              >
                <CardContent className="p-4">
                  <div className="flex items-start gap-4">
                    {/* Type Badge */}
                    <div className="flex flex-col items-center gap-1 pt-1">
                      <Badge
                        variant="outline"
                        className={`text-xs ${typeColors[task.type]} text-white border-0 shrink-0`}
                      >
                        {typeLabels[task.type]}
                      </Badge>
                    </div>

                    {/* Main Content */}
                    <div className="flex-1 min-w-0">
                      {/* Title and Priority */}
                      <div className="flex items-start justify-between gap-2 mb-1">
                        <h4 className="font-medium text-white truncate">{task.title}</h4>
                        <span className={`text-xs font-medium uppercase ${priorityColors[task.priority]} shrink-0`}>
                          {task.priority}
                        </span>
                      </div>

                      {/* Description */}
                      {task.description && (
                        <p className="text-sm text-slate-400 line-clamp-2 mb-3">
                          {task.description}
                        </p>
                      )}

                      {/* Meta Row */}
                      <div className="flex flex-wrap items-center gap-3 text-xs">
                        {/* Status */}
                        <Badge
                          variant="secondary"
                          className={`${statusColors[task.status]} text-white text-[10px] uppercase tracking-wide`}
                        >
                          {formatStatusLabel(task.status)}
                        </Badge>

                        {/* Sprint */}
                        {sprint && (
                          <span className="text-slate-500 flex items-center gap-1">
                            <svg
                              xmlns="http://www.w3.org/2000/svg"
                              className="h-3 w-3"
                              fill="none"
                              viewBox="0 0 24 24"
                              stroke="currentColor"
                            >
                              <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                strokeWidth={2}
                                d="M13 10V3L4 14h7v7l9-11h-7z"
                              />
                            </svg>
                            {sprint.name}
                          </span>
                        )}

                        {/* Comments */}
                        {task.comments && task.comments.length > 0 && (
                          <span className="flex items-center gap-1 text-slate-500">
                            <MessageSquare className="w-3 h-3" />
                            {task.comments.length}
                          </span>
                        )}

                        {/* Attachments */}
                        {attachmentCount > 0 && (
                          <span className="flex items-center gap-1 text-slate-500">
                            <Paperclip className="w-3 h-3" />
                            {attachmentCount}
                          </span>
                        )}

                        {/* Due Date */}
                        {task.dueDate && (
                          <span className="text-slate-500 flex items-center gap-1">
                            <Calendar className="w-3 h-3" />
                            {formatDate(task.dueDate)}
                          </span>
                        )}

                        {/* Tags */}
                        {task.tags && task.tags.length > 0 && (
                          <div className="flex items-center gap-1">
                            {task.tags.slice(0, 3).map((tag) => (
                              <span
                                key={tag}
                                className="text-[10px] px-1.5 py-0.5 bg-slate-800 text-slate-400 rounded"
                              >
                                {tag}
                              </span>
                            ))}
                            {task.tags.length > 3 && (
                              <span className="text-[10px] text-slate-500">+{task.tags.length - 3}</span>
                            )}
                          </div>
                        )}

                        {/* Assignee */}
                        <div className="ml-auto flex items-center gap-2">
                          <AvatarCircle
                            name={task.assigneeName || "Unassigned"}
                            avatarUrl={assignee?.avatarUrl || task.assigneeAvatarUrl}
                            seed={task.assigneeId}
                            sizeClass="h-5 w-5"
                            title={task.assigneeName ? `Assigned to ${task.assigneeName}` : "Unassigned"}
                          />
                          <span className="text-slate-500 hidden sm:inline">
                            {task.assigneeName || "Unassigned"}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>
      )}
    </div>
  )
}
