import { useState, useRef } from 'react'
import { Modal } from '../ui/Modal'
import { Button } from '../ui/Button'
import { useI18n } from '../../i18n/useI18n'

interface ImageAsset {
  id: string
  asset_type: string
  entity_id: string | null
  still_id: string | null
  episode_id: string | null
  file_path: string
  prompt_used: string | null
  status: string
  is_primary: boolean
  created_at: string
}

interface ImageGalleryProps {
  projectId: string
  images: ImageAsset[]
  onSetPrimary: (imageId: string) => void
  onGenerate: () => void
  onUpload?: (file: File) => void
  title: string
  generating?: boolean
}

export function ImageGallery({
  projectId,
  images,
  onSetPrimary,
  onGenerate,
  onUpload,
  title,
  generating = false,
}: ImageGalleryProps) {
  const { t } = useI18n()
  const [zoomImage, setZoomImage] = useState<ImageAsset | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file && onUpload) {
      onUpload(file)
    }
    // Reset input
    if (fileInputRef.current) {
      fileInputRef.current.value = ''
    }
  }

  return (
    <div>
      {/* Header with actions */}
      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: '10px',
      }}>
        <span style={{
          fontSize: '12px',
          fontWeight: 600,
          color: 'var(--text-muted)',
          textTransform: 'uppercase',
          letterSpacing: '0.04em',
        }}>
          {title} ({images.length})
        </span>
        <div style={{ display: 'flex', gap: '6px' }}>
          <Button
            size="sm"
            variant="secondary"
            disabled={generating}
            onClick={onGenerate}
          >
            {generating ? t('still.generating') : t('image.generate_single')}
          </Button>
          {onUpload && (
            <>
              <Button
                size="sm"
                variant="ghost"
                onClick={() => fileInputRef.current?.click()}
              >
                {t('image.upload')}
              </Button>
              <input
                ref={fileInputRef}
                type="file"
                accept="image/*"
                style={{ display: 'none' }}
                onChange={handleFileSelect}
              />
            </>
          )}
        </div>
      </div>

      {/* Image grid */}
      {images.length === 0 ? (
        <div style={{
          padding: '16px',
          textAlign: 'center',
          fontSize: '13px',
          color: 'var(--text-dim)',
          background: 'var(--bg-input)',
          borderRadius: 'var(--radius-sm)',
        }}>
          {t('common.no_data')}
        </div>
      ) : (
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(100px, 1fr))',
          gap: '8px',
        }}>
          {images.map((img) => (
            <div
              key={img.id}
              style={{
                position: 'relative',
                borderRadius: 'var(--radius-sm)',
                overflow: 'hidden',
                border: img.is_primary
                  ? '2px solid var(--green)'
                  : '1px solid var(--border)',
                cursor: 'pointer',
                transition: 'border-color 0.15s',
              }}
              onClick={() => setZoomImage(img)}
            >
              <img
                src={`/api/v1/projects/${projectId}/images/${img.id}/file?thumb=1`}
                alt={img.id}
                style={{
                  width: '100%',
                  height: '80px',
                  objectFit: 'cover',
                  display: 'block',
                }}
                onError={(e) => { (e.target as HTMLImageElement).style.display = 'none' }}
              />
              {/* Primary badge */}
              {img.is_primary && (
                <div style={{
                  position: 'absolute',
                  top: '4px',
                  left: '4px',
                  background: 'var(--green)',
                  color: '#fff',
                  fontSize: '9px',
                  fontWeight: 700,
                  padding: '1px 5px',
                  borderRadius: '999px',
                  letterSpacing: '0.04em',
                }}>
                  {t('image.is_primary')}
                </div>
              )}
              {/* Set primary button (star icon) */}
              {!img.is_primary && (
                <button
                  style={{
                    position: 'absolute',
                    top: '3px',
                    right: '3px',
                    background: 'rgba(0,0,0,0.5)',
                    border: 'none',
                    borderRadius: '999px',
                    width: '20px',
                    height: '20px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    cursor: 'pointer',
                    fontSize: '11px',
                    color: '#fff',
                    padding: 0,
                  }}
                  title={t('image.set_primary')}
                  onClick={(e) => {
                    e.stopPropagation()
                    onSetPrimary(img.id)
                  }}
                >
                  &#9734;
                </button>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Zoom modal */}
      {zoomImage && (
        <Modal
          open={!!zoomImage}
          title={t('image.zoom')}
          onClose={() => setZoomImage(null)}
        >
          <div style={{ textAlign: 'center' }}>
            <img
              src={`/api/v1/projects/${projectId}/images/${zoomImage.id}/file`}
              alt={zoomImage.id}
              style={{ maxWidth: '100%', maxHeight: '70vh' }}
            />
            <div style={{
              display: 'flex',
              gap: '8px',
              justifyContent: 'center',
              marginTop: '12px',
            }}>
              {!zoomImage.is_primary && (
                <Button
                  size="sm"
                  variant="secondary"
                  onClick={() => {
                    onSetPrimary(zoomImage.id)
                    setZoomImage(null)
                  }}
                >
                  {t('image.set_primary')}
                </Button>
              )}
              {zoomImage.is_primary && (
                <span style={{
                  padding: '4px 12px',
                  background: 'var(--green)',
                  color: '#fff',
                  borderRadius: '999px',
                  fontSize: '12px',
                  fontWeight: 600,
                }}>
                  {t('image.is_primary')}
                </span>
              )}
            </div>
          </div>
        </Modal>
      )}
    </div>
  )
}
