import { useRef, useState } from 'react'
import type { StoredSequence } from '../storage/seqStore.ts'

function fmtBytes(n: number): string {
  if (n < 1024) return `${n} B`
  if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`
  return `${(n / (1024 * 1024)).toFixed(1)} MB`
}

export function SequencePanel({
  sequences,
  selectedId,
  onSelect,
  onUpload,
  onRename,
  onDelete,
}: {
  sequences: StoredSequence[]
  selectedId: string | null
  onSelect: (id: string) => void
  onUpload: (files: FileList) => void
  onRename: (id: string, name: string) => void
  onDelete: (id: string) => void
}) {
  const fileRef = useRef<HTMLInputElement>(null)
  const [dragging, setDragging] = useState(false)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [draft, setDraft] = useState('')

  const startEdit = (seq: StoredSequence) => {
    setEditingId(seq.id)
    setDraft(seq.name)
  }
  const commitEdit = () => {
    if (editingId && draft.trim()) onRename(editingId, draft.trim())
    setEditingId(null)
  }

  return (
    <section className="panel">
      <div className="panel-head">
        <h2>Sequences</h2>
        <button type="button" className="btn-small" onClick={() => fileRef.current?.click()}>
          + Upload .seq
        </button>
        <input
          ref={fileRef}
          type="file"
          accept=".seq"
          multiple
          hidden
          onChange={(e) => {
            if (e.target.files?.length) onUpload(e.target.files)
            e.target.value = ''
          }}
        />
      </div>

      <div
        className={`dropzone${dragging ? ' dragging' : ''}`}
        onDragOver={(e) => {
          e.preventDefault()
          setDragging(true)
        }}
        onDragLeave={() => setDragging(false)}
        onDrop={(e) => {
          e.preventDefault()
          setDragging(false)
          if (e.dataTransfer.files?.length) onUpload(e.dataTransfer.files)
        }}
      >
        Drop <code>.seq</code> files here
      </div>

      {sequences.length === 0 ? (
        <p className="muted">
          No sequences yet. Upload a <code>.seq</code> file — for example one exported from{' '}
          <a href="https://concept-collection.github.io/seqlab/" target="_blank" rel="noreferrer">
            seqlab
          </a>
          .
        </p>
      ) : (
        <ul className="seq-list">
          {sequences.map((seq) => (
            <li
              key={seq.id}
              className={seq.id === selectedId ? 'selected' : ''}
              onClick={() => onSelect(seq.id)}
            >
              <div className="seq-row">
                <input
                  type="radio"
                  checked={seq.id === selectedId}
                  onChange={() => onSelect(seq.id)}
                  onClick={(e) => e.stopPropagation()}
                />
                {editingId === seq.id ? (
                  <input
                    className="rename-input"
                    autoFocus
                    value={draft}
                    onChange={(e) => setDraft(e.target.value)}
                    onBlur={commitEdit}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') commitEdit()
                      if (e.key === 'Escape') setEditingId(null)
                    }}
                    onClick={(e) => e.stopPropagation()}
                  />
                ) : (
                  <span className="seq-name" title={seq.name}>
                    {seq.name}
                  </span>
                )}
                <div className="seq-actions" onClick={(e) => e.stopPropagation()}>
                  <button type="button" className="icon-btn" title="Rename" onClick={() => startEdit(seq)}>
                    ✎
                  </button>
                  <button type="button" className="icon-btn danger" title="Delete" onClick={() => onDelete(seq.id)}>
                    🗑
                  </button>
                </div>
              </div>
              <div className="seq-meta">{fmtBytes(seq.size)}</div>
            </li>
          ))}
        </ul>
      )}
    </section>
  )
}
