import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { api } from "../services/api";

export default function AlbumTracksPage() {
  const { albumId } = useParams();
  const [album, setAlbum] = useState(null);
  const [loading, setLoading] = useState(true);

  const [selectedFile, setSelectedFile] = useState(null);
  const [newTrackName, setNewTrackName] = useState("");

  async function loadAlbum() {
    setLoading(true);
    const data = await api.getAlbumById(albumId);
    setAlbum(data);
    setLoading(false);
  }

  useEffect(() => {
    const data = api.getAlbumById(albumId);
    setAlbum(data);
    setLoading(false);
  }, [albumId]);

  function onPickFile(e) {
    const file = e.target.files?.[0] || null;
    setSelectedFile(file);

    if (file) setNewTrackName(file.name);
  }

  async function onAddTrack(e) {
    e.preventDefault();
    if (!selectedFile) return;
    if (!newTrackName.trim()) return;

    await api.addTrack(albumId, { name: newTrackName.trim() });

    setSelectedFile(null);
    setNewTrackName("");
    await loadAlbum();
  }

  async function onEditTrack(index, name) {
    if (!name.trim()) return;
    await api.updateTrack(albumId, index, name.trim());
    await loadAlbum();
  }

  async function onDeleteTrack(index) {
    if (!confirm("Delete this track?")) return;
    await api.deleteTrack(albumId, index);
    await loadAlbum();
  }

  async function onMove(index, direction) {
    const to = direction === "up" ? index - 1 : index + 1;
    await api.moveTrack(albumId, index, to);
    await loadAlbum();
  }

  if (loading) return <p>Loading...</p>;
  if (!album) return <p>Album not found.</p>;

  return (
    <section>
      <div style={{ marginBottom: 12 }}>
        <Link to="/albums" className="tab">← Back to Albums</Link>
      </div>

      <h2>Tracks — {album.title}</h2>
      <p className="muted">{album.artist}</p>

      <form className="card form" onSubmit={onAddTrack}>
        <h3>Add Track</h3>

        <label className="fileLabel">
          Select audio file
          <input
            type="file"
            accept=".mp3,.wav,.flac,audio/*"
            onChange={onPickFile}
          />
        </label>

        <input
          placeholder="Track name"
          value={newTrackName}
          onChange={(e) => setNewTrackName(e.target.value)}
        />

        <div style={{ marginTop: 10 }}>
          <button className="btn primary" type="submit" disabled={!selectedFile || !newTrackName.trim()}>
            Add Track
          </button>
        </div>
      </form>

      <div className="list">
        {(album.tracks || []).length === 0 ? (
          <p>No tracks yet.</p>
        ) : (
          album.tracks.map((track, index) => (
            <TrackRow
              key={`${track.name}-${index}`}
              track={track}
              index={index}
              total={album.tracks.length}
              onEdit={onEditTrack}
              onDelete={onDeleteTrack}
              onMove={onMove}
            />
          ))
        )}
      </div>
    </section>
  );
}

function TrackRow({ track, index, total, onEdit, onDelete, onMove }) {
  const [name, setName] = useState(track.name);

  useEffect(() => {
    setName(track.name);
  }, [track.name]);

  return (
    <div className="card row">
      <div style={{ flex: 1, textAlign: "left" }}>
        <div className="muted">#{index + 1}</div>
        <input
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Track name"
        />
      </div>

      <div className="actions">
        <button
          type="button"
          className="btn secondary"
          onClick={() => onMove(index, "up")}
          disabled={index === 0}
        >
          Move up
        </button>
        <button
          type="button"
          className="btn secondary"
          onClick={() => onMove(index, "down")}
          disabled={index === total - 1}
        >
          Move down
        </button>
        <button type="button" className="btn primary" onClick={() => onEdit(index, name)}>
          Save
        </button>
        <button type="button" className="btn danger" onClick={() => onDelete(index)}>
          Delete
        </button>
      </div>
    </div>
  );
}