import { useEffect, useState } from 'react'
import { api } from '../api'
import Modal from './Modal'
import { ACCEPT_GLYPH, REJECT_GLYPH } from './Thumbs'

export default function XmpModal({ albumId, onClose }) {
  const [shares, setShares] = useState(null)
  const [own, setOwn] = useState(true)
  const [checked, setChecked] = useState(() => new Set())
  const [error, setError] = useState(null)

  useEffect(() => {
    api(`/api/albums/${albumId}/shares`)
      .then((list) => {
        setShares(list)
        setChecked(new Set(list.map((s) => s.id)))
      })
      .catch((e) => setError(e.message))
  }, [albumId])

  const toggleShare = (id) =>
    setChecked((prev) => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })

  // Disabled until the share list is loaded — before that, "everything
  // checked" can't be expressed and a click would export too little.
  const disabled = shares == null || (checked.size === 0 && !own)
  const url = `/api/albums/${albumId}/xmp?${new URLSearchParams({
    shares: [...checked].join(','),
    own: String(own),
  })}`

  const counts = (s) =>
    [
      s.accept_count > 0 && `${ACCEPT_GLYPH} ${s.accept_count}`,
      s.reject_count > 0 && `${REJECT_GLYPH} ${s.reject_count}`,
      s.rating_count > 0 && `★ ${s.rating_count}`,
      s.tag_count > 0 && `# ${s.tag_count}`,
    ]
      .filter(Boolean)
      .join(' · ') || 'no feedback yet'

  return (
    <Modal title="XMP export" onClose={onClose}>
      <p className="muted">
        Sidecar files for Capture One/Lightroom — unzip next to the RAWs, then load metadata.
        Ratings merge as the highest vote across the selected sources; any accept wins over
        rejects.
      </p>
      <label className="select-toggle xmp-source">
        <input type="checkbox" checked={own} onChange={(e) => setOwn(e.target.checked)} />
        you
        <span className="muted">your votes and ratings</span>
      </label>
      {(shares ?? []).map((s) => (
        <label key={s.id} className="select-toggle xmp-source">
          <input type="checkbox" checked={checked.has(s.id)} onChange={() => toggleShare(s.id)} />
          {s.label || 'unnamed link'}
          <span className="muted">{counts(s)}</span>
        </label>
      ))}
      <div className="row modal-foot">
        <a
          className={`btn btn-primary${disabled ? ' btn-disabled' : ''}`}
          href={disabled ? undefined : url}
          onClick={(e) => {
            if (disabled) e.preventDefault()
          }}
        >
          Download XMP
        </a>
      </div>
      {error && <p className="error">{error}</p>}
    </Modal>
  )
}
