"use client";

import Link from "next/link";
import { ChevronRight, FileText, Folder, MoreHorizontal, Pin, PinOff, Plus, Trash2 } from "lucide-react";
import {
  Dropdown,
  DropdownContent,
  DropdownItem,
  DropdownTrigger,
} from "@/components/ui/dropdown";
import { extractNotePreview } from "@/lib/notes/note-preview";
import { useNoteDesigns } from "@/hooks/use-note-designs";
import { cn } from "@/lib/utils";
import type { NoteWithRelations } from "@/hooks/use-notes";
import type { NoteFolder } from "@/types";

interface NoteListRowProps {
  note: NoteWithRelations;
  folder?: NoteFolder | null;
  onTogglePin: () => void;
  onDelete: () => void;
  canManage?: boolean;
  // Sub-page hierarchy — a note with children shows a chevron so it can
  // be expanded/collapsed like a Notion page list, with children indented
  // underneath once expanded.
  depth?: number;
  hasChildren?: boolean;
  expanded?: boolean;
  onToggleExpand?: () => void;
  onCreateSubPage?: () => void;
}

function formatRelativeDate(value: string) {
  const date = new Date(value);
  const diffMs = Date.now() - date.getTime();
  const diffMins = Math.round(diffMs / 60_000);

  if (diffMins < 1) return "just now";
  if (diffMins < 60) return `${diffMins}m ago`;
  const diffHours = Math.round(diffMins / 60);
  if (diffHours < 24) return `${diffHours}h ago`;
  const diffDays = Math.round(diffHours / 24);
  if (diffDays < 7) return `${diffDays}d ago`;

  return date.toLocaleDateString("de-DE", { day: "2-digit", month: "short", year: "numeric" });
}

export function NoteListRow({
  note,
  folder,
  onTogglePin,
  onDelete,
  canManage = true,
  depth = 0,
  hasChildren = false,
  expanded = false,
  onToggleExpand,
  onCreateSubPage,
}: NoteListRowProps) {
  const preview = extractNotePreview(note.content);
  const { getCover } = useNoteDesigns();
  const cover = getCover(note.cover_id);

  return (
    <div
      className="group flex items-center gap-1.5 border-b border-white/[0.05] py-2.5 pr-3 transition-colors last:border-b-0 hover:bg-white/[0.03]"
      style={{ paddingLeft: `${depth * 22 + 12}px` }}
    >
      <button
        type="button"
        onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
          onToggleExpand?.();
        }}
        className={cn(
          "flex h-5 w-5 shrink-0 items-center justify-center rounded transition-transform hover:bg-white/[0.06]",
          !hasChildren && "invisible",
        )}
      >
        <ChevronRight className={cn("h-3.5 w-3.5 text-white/35 transition-transform", expanded && "rotate-90")} />
      </button>

      <Link href={`/notes/${note.id}`} className="flex min-w-0 flex-1 items-center gap-3">
        <span
          className={cn(
            "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border text-white/30",
            cover ? "border-white/[0.12] text-white/80" : "border-white/[0.06] bg-white/[0.03]",
          )}
          style={cover?.style}
        >
          {note.is_pinned ? <Pin className="h-3.5 w-3.5 fill-teal-400 text-teal-400" /> : <FileText className="h-3.5 w-3.5" />}
        </span>

        <span className="min-w-0 flex-1">
          <span className="flex items-center gap-2">
            <span className="truncate text-[13.5px] font-medium text-white/85">
              {note.title || "Untitled"}
            </span>
            {note.tags.slice(0, 2).map((tag) => (
              <span
                key={tag.id}
                className="hidden shrink-0 rounded-full px-1.5 py-0 text-[10px] font-medium sm:inline-flex"
                style={{ backgroundColor: tag.color + "18", color: tag.color }}
              >
                {tag.name}
              </span>
            ))}
          </span>
          {preview && (
            <span className="mt-0.5 hidden truncate text-[12px] text-white/30 md:block">{preview}</span>
          )}
        </span>

        {folder && (
          <span className="hidden shrink-0 items-center gap-1 rounded-full border border-white/[0.06] bg-white/[0.03] px-2 py-0.5 text-[11px] text-white/35 lg:flex">
            <Folder className="h-2.5 w-2.5" />
            {folder.name}
          </span>
        )}

        <span className="shrink-0 text-[11px] text-white/25">{formatRelativeDate(note.updated_at)}</span>
      </Link>

      {canManage && onCreateSubPage && (
        <button
          type="button"
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            onCreateSubPage();
          }}
          title="Add sub-page"
          className="shrink-0 rounded-md p-1.5 text-white/25 opacity-0 transition-opacity hover:bg-white/[0.06] hover:text-white/60 group-hover:opacity-100"
        >
          <Plus className="h-4 w-4" />
        </button>
      )}

      {canManage && (
        <Dropdown>
          <DropdownTrigger
            className={cn(
              "shrink-0 rounded-md p-1.5 text-white/25 opacity-0 transition-opacity hover:bg-white/[0.06] hover:text-white/60 group-hover:opacity-100",
            )}
          >
            <MoreHorizontal className="h-4 w-4" />
          </DropdownTrigger>
          <DropdownContent>
            <DropdownItem onClick={onTogglePin}>
              {note.is_pinned ? <PinOff className="h-3.5 w-3.5" /> : <Pin className="h-3.5 w-3.5" />}
              {note.is_pinned ? "Unpin" : "Pin"}
            </DropdownItem>
            <DropdownItem onClick={onDelete} destructive>
              <Trash2 className="h-3.5 w-3.5" />
              Delete
            </DropdownItem>
          </DropdownContent>
        </Dropdown>
      )}
    </div>
  );
}
