"use client"

import React from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { MessageSquare, Calendar, Paperclip, Hash } from "lucide-react"
import { Task, TaskType, TaskStatus } from "@/stores/useTaskStore"
import { HighlightText, HighlightMatches } from "./HighlightText"
import { generateAvatarDataUrl } from "@/lib/avatar"

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

const typeLabels: Record<TaskType, 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 formatStatusLabel = (status: TaskStatus) =>
  status === "todo"
    ? "To Do"
    : status
        .split("-")
        .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
        .join(" ")

interface TaskSearchItemProps {
  task: Task
  query: string
  sprintName?: string | null
  onClick?: () => void
}

function AvatarCircle({
  name,
  avatarUrl,
  seed,
  sizeClass = "h-5 w-5",
}: {
  name?: string
  avatarUrl?: string
  seed?: string
  sizeClass?: 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`}
    />
  )
}

export function TaskSearchItem({ task, query, sprintName, onClick }: TaskSearchItemProps) {
  const router = useRouter()
  const attachmentCount = task.attachments?.length || 0

  const handleClick = () => {
    if (onClick) {
      onClick()
    } else {
      router.push(`/tasks/${encodeURIComponent(task.id)}`)
    }
  }

  // Build matches for highlighting
  const matchFields = [
    { field: "Description", value: task.description || "" },
    { field: "Tags", value: task.tags?.join(", ") || "" },
  ]

  const hasMatchInField = (fieldValue: string) => {
    if (!query.trim()) return false
    return fieldValue.toLowerCase().includes(query.toLowerCase())
  }

  return (
    <Card
      className="bg-slate-900 border-slate-800 hover:border-blue-500/50 cursor-pointer transition-all group"
      onClick={handleClick}
    >
      <CardContent className="p-4">
        <div className="flex items-start gap-3">
          {/* Type Badge */}
          <div className="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 Row */}
            <div className="flex items-start justify-between gap-2 mb-2">
              <h4 className="font-medium text-white truncate">
                <HighlightText text={task.title} query={query} />
              </h4>
              <span className={`text-xs font-medium uppercase ${priorityColors[task.priority]} shrink-0`}>
                {task.priority}
              </span>
            </div>

            {/* Highlighted Match Display */}
            <HighlightMatches
              matches={matchFields}
              query={query}
              className="mb-3 space-y-1"
              maxLength={150}
            />

            {/* Individual Tag Highlights (if tags match) */}
            {task.tags && task.tags.length > 0 && hasMatchInField(task.tags.join(" ")) && (
              <div className="flex flex-wrap gap-1.5 mb-3">
                {task.tags.map((tag) => {
                  const isMatch = hasMatchInField(tag)
                  return (
                    <span
                      key={tag}
                      className={`text-xs px-2 py-0.5 rounded flex items-center gap-1 ${
                        isMatch
                          ? "bg-yellow-500/20 text-yellow-300 border border-yellow-500/30"
                          : "bg-slate-800 text-slate-400"
                      }`}
                    >
                      <Hash className="w-3 h-3" />
                      {isMatch ? <HighlightText text={tag} query={query} /> : tag}
                    </span>
                  )
                })}
              </div>
            )}

            {/* Meta Row */}
            <div className="flex flex-wrap items-center gap-3 text-xs text-slate-500">
              {/* Status */}
              <Badge
                variant="secondary"
                className="bg-slate-800 text-slate-300 text-[10px]"
              >
                {formatStatusLabel(task.status)}
              </Badge>

              {/* Sprint */}
              {sprintName && (
                <span className="flex items-center gap-1">
                  <Calendar className="w-3 h-3" />
                  {sprintName}
                </span>
              )}

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

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

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

              {/* Assignee */}
              <div className="ml-auto flex items-center gap-2">
                <AvatarCircle
                  name={task.assigneeName || "Unassigned"}
                  avatarUrl={task.assigneeAvatarUrl}
                  seed={task.assigneeId}
                  sizeClass="h-5 w-5"
                />
                <span className="hidden sm:inline">
                  {task.assigneeName ? (
                    hasMatchInField(task.assigneeName) ? (
                      <HighlightText text={task.assigneeName} query={query} />
                    ) : (
                      task.assigneeName
                    )
                  ) : (
                    "Unassigned"
                  )}
                </span>
              </div>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

export default TaskSearchItem
