'use client'

import { useEffect, useRef, useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
import { MapPin, Trash2, Pencil, Check, X as XIcon } from 'lucide-react'
import { renameLocationAction } from '@/app/locations/actions'

interface Props {
  locationId: string
  locationName: string
  locationPath: string
  itemCount: number
  hasOwnMap: boolean
  onRemove: () => void
  busy: boolean
}

export function PinRow({
  locationId,
  locationName,
  locationPath,
  itemCount,
  hasOwnMap,
  onRemove,
  busy,
}: Props) {
  const [editing, setEditing] = useState(false)
  const [draft, setDraft] = useState(locationName)
  const [pending, startTransition] = useTransition()
  const inputRef = useRef<HTMLInputElement>(null)
  const router = useRouter()

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

  // Parent prefix shown under the editable name.
  const parentPath = locationPath.includes(' > ')
    ? locationPath.substring(0, locationPath.lastIndexOf(' > '))
    : null

  const save = () => {
    const trimmed = draft.trim()
    if (!trimmed || trimmed === locationName) {
      setDraft(locationName)
      setEditing(false)
      return
    }
    startTransition(async () => {
      await renameLocationAction(locationId, trimmed)
      router.refresh()
      setEditing(false)
    })
  }

  return (
    <div className="flex items-center gap-2 p-2">
      <MapPin className="size-4 text-muted-foreground shrink-0" />
      <div className="flex-1 min-w-0">
        {editing ? (
          <input
            ref={inputRef}
            value={draft}
            onChange={e => setDraft(e.target.value)}
            onBlur={save}
            onKeyDown={e => {
              if (e.key === 'Enter') {
                e.preventDefault()
                save()
              } else if (e.key === 'Escape') {
                setDraft(locationName)
                setEditing(false)
              }
            }}
            disabled={pending}
            className="w-full text-sm bg-background border rounded-md px-2 py-0.5 outline-none focus:ring-2 focus:ring-ring"
            autoFocus
          />
        ) : (
          <button
            type="button"
            onClick={() => setEditing(true)}
            className="text-sm truncate flex items-center gap-1.5 hover:text-foreground group text-left max-w-full"
            title="Rename"
          >
            <span className="truncate">{locationName}</span>
            <Pencil className="size-3 text-muted-foreground opacity-0 group-hover:opacity-100 shrink-0" />
          </button>
        )}
        <div className="text-xs text-muted-foreground truncate">
          {parentPath && <span>{parentPath} · </span>}
          {itemCount} item{itemCount === 1 ? '' : 's'}
          {hasOwnMap && ' · has interior map'}
        </div>
      </div>
      {editing ? (
        <>
          <button
            type="button"
            onMouseDown={e => e.preventDefault()}
            onClick={save}
            disabled={pending}
            aria-label="Save name"
            className="size-9 rounded-lg border text-emerald-600 hover:bg-emerald-50 dark:hover:bg-emerald-950/30 flex items-center justify-center"
          >
            <Check className="size-4" />
          </button>
          <button
            type="button"
            onMouseDown={e => e.preventDefault()}
            onClick={() => {
              setDraft(locationName)
              setEditing(false)
            }}
            disabled={pending}
            aria-label="Cancel rename"
            className="size-9 rounded-lg border text-muted-foreground hover:text-foreground flex items-center justify-center"
          >
            <XIcon className="size-4" />
          </button>
        </>
      ) : (
        <button
          type="button"
          onClick={onRemove}
          disabled={busy}
          aria-label="Remove pin"
          className="size-9 rounded-lg border text-muted-foreground hover:text-rose-600 flex items-center justify-center"
        >
          <Trash2 className="size-4" />
        </button>
      )}
    </div>
  )
}
