import { useTranslation } from 'react-i18next'
import { FaPen } from 'react-icons/fa'
import { AnnotationStatus } from '../../types'
import type { Detection } from '../../types'

export interface DatasetCard {
  annotationId: string
  imageName: string
  status: AnnotationStatus
  createdDate: string
  thumbnailUrl: string
  isSeed: boolean
  isLocal: boolean
  detections?: Detection[]
  mediaId?: string
  time?: string | null
  fullFrame?: string
  annotationLocalId?: string
}

interface DatasetTileProps {
  card: DatasetCard
  isSelected: boolean
  onClick: (e: React.MouseEvent) => void
  onDoubleClick: () => void
  onContextMenu: (e: React.MouseEvent) => void
  onEditClick: () => void
}

const TILE_DATE_FMT = new Intl.DateTimeFormat('en', { day: '2-digit', month: 'short' })

export function formatTileDate(iso: string): string {
  try {
    const d = new Date(iso)
    if (isNaN(d.getTime())) return ''
    return TILE_DATE_FMT.format(d).toUpperCase()
  } catch {
    return ''
  }
}

export default function DatasetTile({
  card,
  isSelected,
  onClick,
  onDoubleClick,
  onContextMenu,
  onEditClick,
}: DatasetTileProps) {
  const { t } = useTranslation()

  const statusPill =
    card.status === AnnotationStatus.Validated
      ? { cls: 'pill-green', label: t('dataset.status.validated') }
      : card.status === AnnotationStatus.Edited
        ? { cls: 'pill-blue', label: t('dataset.status.edited') }
        : card.status === AnnotationStatus.Created
          ? { cls: 'pill-amber', label: t('dataset.status.created') }
          : { cls: 'pill-muted', label: t('dataset.status.none') }

  const borderCls = isSelected
    ? card.isSeed
      ? 'border-2 border-accent-amber ring-1 ring-accent-red'
      : 'border-2 border-accent-amber'
    : card.isSeed
      ? 'border border-accent-red'
      : 'border border-border-hair hover:border-accent-amber'

  const tileDate = formatTileDate(card.createdDate)

  return (
    <div
      onClick={onClick}
      onDoubleClick={onDoubleClick}
      onContextMenu={onContextMenu}
      title={card.imageName}
      className={`group aspect-square relative overflow-hidden rounded-[2px] bg-surface-1 cursor-pointer transition-colors ${borderCls}`}
    >
      {card.thumbnailUrl ? (
        <img
          src={card.thumbnailUrl}
          alt={card.imageName}
          loading="lazy"
          className="absolute inset-0 w-full h-full object-cover bg-surface-0"
        />
      ) : (
        <div className="absolute inset-0 bg-surface-0" />
      )}

      {/* composite scrim: grid lines + bottom fade (matches design .tile .scrim) */}
      <div
        className="absolute inset-0 pointer-events-none"
        style={{
          backgroundImage:
            'linear-gradient(rgba(255,255,255,0.025) 1px, transparent 1px),' +
            'linear-gradient(90deg, rgba(255,255,255,0.025) 1px, transparent 1px),' +
            'linear-gradient(180deg, rgba(0,0,0,0) 55%, rgba(0,0,0,0.55) 100%)',
          backgroundSize: '24px 24px, 24px 24px, 100% 100%',
        }}
      />

      {/* corner-tag top-right */}
      {tileDate && (
        <div
          className="absolute top-1.5 right-1.5 font-mono text-[9px] tracking-wider text-text-primary border border-border-hair rounded-[2px]"
          style={{ background: 'rgba(10,13,16,0.65)', padding: '1px 5px' }}
        >
          {tileDate}
        </div>
      )}

      {/* local badge — top-left */}
      {card.isLocal && (
        <div
          className="absolute top-1.5 left-1.5 font-mono text-[9px] tracking-wider text-accent-cyan border border-accent-cyan/50 rounded-[2px] px-1.5 py-px"
          style={{ background: 'rgba(10,13,16,0.65)' }}
        >
          {t('dataset.local').toUpperCase()}
        </div>
      )}

      {/* selected check badge (only when selected & not local — local already has top-left badge) */}
      {isSelected && !card.isLocal && (
        <div
          className="absolute top-1 left-1 inline-flex items-center justify-center rounded-[2px] bg-accent-amber"
          style={{ width: 14, height: 14, color: '#0A0D10' }}
        >
          <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.5">
            <polyline points="20 6 9 17 4 12" />
          </svg>
        </div>
      )}

      {/* status pill bottom-left */}
      <span
        className={`absolute bottom-1.5 left-1.5 pill ${statusPill.cls}`}
        style={{ padding: '2px 6px', fontSize: 9, height: 'auto', lineHeight: 1 }}
      >
        <span className="dot" />
        {statusPill.label}
      </span>

      {/* edit ibtn bottom-right (reveal on hover) */}
      <button
        type="button"
        onClick={e => { e.stopPropagation(); onEditClick() }}
        title={t('dataset.edit')}
        className="ibtn edit absolute bottom-1.5 right-1.5 opacity-0 group-hover:opacity-100 transition-opacity"
        style={{ background: 'rgba(10,13,16,0.65)' }}
      >
        <FaPen size={9} />
      </button>
    </div>
  )
}
