'use client'

import { useState } from 'react'
import { Note } from '@/lib/types'
import { NoteCard } from './note-card'
import { ChevronDown, ChevronUp, Pin } from 'lucide-react'
import { useLanguage } from '@/lib/i18n'

interface FavoritesSectionProps {
  pinnedNotes: Note[]
  onEdit?: (note: Note, readOnly?: boolean) => void
  onSizeChange?: (noteId: string, size: 'small' | 'medium' | 'large') => void
  isLoading?: boolean
}

export function FavoritesSection({ pinnedNotes, onEdit, onSizeChange, isLoading }: FavoritesSectionProps) {
  const [isCollapsed, setIsCollapsed] = useState(false)
  const { t } = useLanguage()

  if (isLoading) {
    return (
      <section data-testid="favorites-section" className="mb-8">
        <div className="flex items-center gap-2 mb-4 px-2 py-2">
          <Pin className="w-5 h-5 text-muted-foreground animate-pulse" />
          <div className="h-6 w-32 bg-muted rounded animate-pulse" />
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {[1, 2, 3].map((i) => (
            <div key={i} className="h-40 bg-muted rounded-2xl animate-pulse" />
          ))}
        </div>
      </section>
    )
  }

  if (pinnedNotes.length === 0) {
    return null
  }

  return (
    <section data-testid="favorites-section" className="mb-8">
      <button
        onClick={() => setIsCollapsed(!isCollapsed)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault()
            setIsCollapsed(!isCollapsed)
          }
        }}
        className="w-full flex items-center justify-between gap-2 mb-4 px-2 py-2 hover:bg-accent rounded-lg transition-colors min-h-[44px]"
        aria-expanded={!isCollapsed}
        aria-label={t('favorites.toggleSection') || 'Toggle pinned notes section'}
      >
        <div className="flex items-center gap-2">
          <span className="text-2xl">📌</span>
          <h2 className="text-lg font-semibold text-foreground">
            {t('notes.pinnedNotes')}
            <span className="text-sm font-medium text-muted-foreground ml-2">
              ({pinnedNotes.length})
            </span>
          </h2>
        </div>
        {isCollapsed ? (
          <ChevronDown className="w-5 h-5 text-muted-foreground" />
        ) : (
          <ChevronUp className="w-5 h-5 text-muted-foreground" />
        )}
      </button>

      {/* Collapsible Content */}
      {!isCollapsed && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {pinnedNotes.map((note) => (
            <NoteCard
              key={note.id}
              note={note}
              onEdit={onEdit}
              onSizeChange={(size) => onSizeChange?.(note.id, size)}
            />
          ))}
        </div>
      )}
    </section>
  )
}
