import { useState, useMemo, useCallback } from 'react'
import { Tag as TagIcon, ArrowLeft, Loader2 } from 'lucide-react'
import clsx from 'clsx'
import { Button } from '@/components/ui/button'
import { useTagsQuery } from '../../hooks/useTagsQuery'
import { photos as photosApi, type Tag } from '../../services/api'
import { useFilterStore } from '../../store/filterStore'
import { useCardGridNav } from '../../hooks/useCardGridNav'
import { Timeline } from '../timeline/Timeline'

/**
 * Tags view — two states:
 * 1. Grid of tag cards (default) — arrow keys + Enter to browse
 * 2. Detail view showing a tag's photos in the full Timeline — Esc to go back
 */
export function TagsView() {
  const { data: allTags = [], isLoading } = useTagsQuery()
  const setTagIds = useFilterStore((s) => s.setTagIds)
  const [selectedTag, setSelectedTag] = useState<Tag | null>(null)

  const tags = useMemo(
    () =>
      allTags
        .filter((t) => t.kind === 'user')
        .sort((a, b) => b.photo_count - a.photo_count),
    [allTags]
  )

  const enterDetail = useCallback(
    (tag: Tag) => {
      setTagIds([tag.id])
      setSelectedTag(tag)
    },
    [setTagIds]
  )

  const exitDetail = useCallback(() => {
    setTagIds([])
    setSelectedTag(null)
  }, [setTagIds])

  const { activeIndex, gridRef } = useCardGridNav({
    items: tags,
    inDetail: selectedTag !== null,
    onEnter: enterDetail,
    onExit: exitDetail,
  })

  if (selectedTag) {
    return (
      <div className="flex h-full flex-col overflow-hidden">
        <div className="flex items-center gap-3 border-b border-border px-4 py-3">
          <Button
            variant="ghost"
            size="icon"
            className="h-7 w-7 text-text-muted"
            onClick={exitDetail}
            title="Back to tags"
          >
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <h2 className="text-sm font-semibold text-text">{selectedTag.name}</h2>
        </div>
        <div className="flex-1 overflow-hidden">
          <Timeline />
        </div>
      </div>
    )
  }

  if (isLoading) {
    return (
      <div className="flex h-full items-center justify-center text-text-muted">
        <Loader2 className="mr-2 h-5 w-5 animate-spin" />
        Loading tags...
      </div>
    )
  }

  if (tags.length === 0) {
    return (
      <div className="flex h-full flex-col items-center justify-center gap-3 text-text-muted">
        <TagIcon className="h-12 w-12 opacity-40" />
        <p className="text-sm">No tags yet</p>
        <p className="max-w-xs text-center text-xs opacity-70">
          Tags will appear here once photos are tagged — either manually or by
          the auto-tagger.
        </p>
      </div>
    )
  }

  return (
    <div className="h-full overflow-auto p-4 pb-20">
      <div className="mb-4 flex items-center gap-2 text-text-muted">
        <TagIcon className="h-4 w-4" />
        <span className="text-sm font-medium">
          {tags.length} {tags.length === 1 ? 'tag' : 'tags'}
        </span>
      </div>

      <div
        ref={gridRef}
        className="grid grid-cols-[repeat(auto-fill,minmax(140px,1fr))] gap-3"
      >
        {tags.map((tag, i) => (
          <div
            key={tag.id}
            className={clsx(
              'group cursor-pointer overflow-hidden rounded-lg border bg-surface transition-all hover:border-primary/50 hover:shadow-md',
              i === activeIndex
                ? 'border-primary ring-1 ring-primary/30'
                : 'border-border'
            )}
            onClick={() => enterDetail(tag)}
          >
            <div className="relative aspect-square overflow-hidden bg-surface-2">
              {tag.representative_photo_id ? (
                <img
                  src={photosApi.getThumbnailUrl(tag.representative_photo_id, 'small')}
                  alt={tag.name}
                  className="h-full w-full object-cover"
                />
              ) : (
                <div className="flex h-full w-full items-center justify-center">
                  <TagIcon className="h-10 w-10 text-text-muted/30" />
                </div>
              )}

              <span className="absolute bottom-1.5 right-1.5 rounded-full bg-black/60 px-2 py-0.5 text-[11px] font-medium text-white backdrop-blur-sm">
                {tag.photo_count}
              </span>
            </div>

            <div className="px-2 py-1.5">
              <p className="truncate text-xs font-medium text-text">{tag.name}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
