"use client";

import { useState, useRef, useEffect } from "react";
import { FolderOpen, FileCode2, Globe, Trash2, ChevronRight, Pencil, Check, X, Archive } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card";
import type { PageInfo } from "@/lib/api/pages";

type PageRowProps = {
  page: PageInfo;
  childCount?: number;
  onNavigate: (id: string) => void;
  onDelete: (id: string) => void;
  onRename: (id: string, name: string) => void;
};

function formatSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  return `${(bytes / 1024).toFixed(1)} KB`;
}

function extractDomain(url: string): string {
  try {
    return new URL(url).hostname;
  } catch {
    return url;
  }
}

export function PageRow({ page, childCount, onNavigate, onDelete, onRename }: PageRowProps) {
  const isFolder = page.content_type === "folder";
  const isUrl = page.content_type === "url";
  const isBundle = page.content_type === "bundle";
  const Icon = isFolder ? FolderOpen : isUrl ? Globe : isBundle ? Archive : FileCode2;

  const iconColor = isFolder
    ? "text-amber-400"
    : isUrl
      ? "text-violet-400"
      : isBundle
        ? "text-emerald-400"
        : "text-sky-400";

  const [editing, setEditing] = useState(false);
  const [editName, setEditName] = useState(page.name);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (editing) {
      inputRef.current?.focus();
      inputRef.current?.select();
    }
  }, [editing]);

  const handleClick = () => {
    if (editing) return;
    onNavigate(page.id);
  };

  const startEditing = () => {
    setEditName(page.name);
    setEditing(true);
  };

  const commitRename = () => {
    const trimmed = editName.trim();
    if (trimmed && trimmed !== page.name) {
      onRename(page.id, trimmed);
    }
    setEditing(false);
  };

  const cancelEditing = () => {
    setEditName(page.name);
    setEditing(false);
  };

  return (
    <div
      className="group flex items-center gap-4 px-5 py-3.5 border-b border-foreground/5 hover:bg-foreground/[0.03] transition-colors cursor-pointer"
      onClick={handleClick}
    >
      {/* Icon */}
      <Icon className={`w-4 h-4 shrink-0 ${iconColor}`} />

      {/* Name: inline edit or hover card */}
      {editing ? (
        <div className="flex items-center gap-1.5 min-w-0 flex-shrink" onClick={(e) => e.stopPropagation()}>
          <Input
            ref={inputRef}
            value={editName}
            onChange={(e) => setEditName(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") commitRename();
              if (e.key === "Escape") cancelEditing();
            }}
            className="h-7 text-sm font-bold bg-background border-foreground/10 px-2 py-0 rounded-sm w-48"
          />
          <Button
            variant="ghost"
            size="icon"
            className="h-7 w-7 text-emerald-400 hover:text-emerald-300 hover:bg-emerald-500/10"
            onClick={commitRename}
          >
            <Check className="w-3.5 h-3.5" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            className="h-7 w-7 text-muted-foreground hover:text-foreground"
            onClick={cancelEditing}
          >
            <X className="w-3.5 h-3.5" />
          </Button>
        </div>
      ) : (
        <HoverCard openDelay={300} closeDelay={100}>
          <HoverCardTrigger asChild>
            <span className="font-bold text-sm text-foreground truncate hover:text-primary transition-colors min-w-0 flex-shrink cursor-pointer">
              {page.name}
            </span>
          </HoverCardTrigger>
          <HoverCardContent side="bottom" align="start" className="w-72 bg-popover/95 backdrop-blur-xl border-foreground/10">
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <Icon className={`w-4 h-4 ${iconColor}`} />
                <span className="font-black text-sm">{page.name}</span>
              </div>
              {page.description && (
                <p className="text-xs text-foreground/60 leading-relaxed">{page.description}</p>
              )}
              {isUrl && page.url && (
                <code className="text-[11px] font-mono text-foreground/50 break-all block">{page.url}</code>
              )}
              {!isFolder && !isUrl && page.filename && (
                <div className="flex justify-between text-[11px] font-mono text-foreground/50">
                  <span>{page.filename}</span>
                  <span>{formatSize(page.size_bytes)}</span>
                </div>
              )}
              {isFolder && childCount !== undefined && (
                <span className="text-[11px] font-mono text-foreground/50">{childCount} items</span>
              )}
            </div>
          </HoverCardContent>
        </HoverCard>
      )}

      {/* Meta info */}
      {!editing && (
        <>
          {isFolder ? (
            <>
              {page.description && (
                <span className="text-xs text-muted-foreground/50 truncate hidden sm:block max-w-[200px]">
                  {page.description}
                </span>
              )}
              {childCount !== undefined && (
                <span className="text-[10px] font-mono text-muted-foreground/40 shrink-0">{childCount} items</span>
              )}
            </>
          ) : isUrl && page.url ? (
            <span className="text-[10px] font-mono text-muted-foreground/40 truncate shrink-0 max-w-[200px]">
              {extractDomain(page.url)}
            </span>
          ) : (
            <span className="text-[10px] font-mono text-muted-foreground/40 shrink-0">
              {formatSize(page.size_bytes)}
            </span>
          )}
        </>
      )}

      {/* Spacer */}
      <div className="flex-1" />

      {/* Action buttons - visible on hover */}
      {!editing && (
        <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0" onClick={(e) => e.stopPropagation()}>
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8 text-muted-foreground hover:text-primary hover:bg-primary/10"
            onClick={startEditing}
            title="Rename"
          >
            <Pencil className="w-3.5 h-3.5" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8 text-muted-foreground hover:text-destructive hover:bg-destructive/10"
            onClick={() => onDelete(page.id)}
            title="Delete"
          >
            <Trash2 className="w-3.5 h-3.5" />
          </Button>
        </div>
      )}

      {/* Folder arrow */}
      {isFolder && !editing && (
        <ChevronRight className="w-4 h-4 text-muted-foreground/30 shrink-0" />
      )}
    </div>
  );
}
