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

const API_BASE = import.meta.env.VITE_API_URL?.replace(/\/api\/?$/, "") || "";

function getArtistName(album) {
  if (album.artist?.name) return album.artist.name;
  const names = new Set();
  (album.tracks || []).forEach((t) =>
    (t.artists || []).forEach((a) => names.add(a.name))
  );
  return [...names].join(", ") || "Unknown artist";
}

function getGenreNames(album) {
  if (album.genres?.length > 0) return album.genres.map((g) => g.name).join(", ");
  const names = new Set();
  (album.tracks || []).forEach((t) =>
    (t.genres || []).forEach((g) => names.add(g.name))
  );
  return [...names].join(", ") || "No genre";
}

export default function AlbumsPage() {
  const navigate = useNavigate();
  const [query, setQuery] = useState("");
  const [sortBy, setSortBy] = useState("newest");
  const [page, setPage] = useState(1);
  const pageSize = 5;
  const [albums, setAlbums] = useState([]);
  const [loading, setLoading] = useState(true);

  const [artists, setArtists] = useState([]);
  const [genres, setGenres] = useState([]);
  const [form, setForm] = useState({
    title: "",
    type: "album",
    releaseDate: "",
    artistId: "",
    newArtist: "",
    genreIds: [],
    newGenre: "",
  });
  const [coverFile, setCoverFile] = useState(null);
  const [submitting, setSubmitting] = useState(false);

  async function loadAlbums() {
    setLoading(true);
    try {
      const data = await api.getAlbums();
      setAlbums(data);
    } catch (err) {
      console.error("Failed to load albums:", err);
    }
    setLoading(false);
  }

  async function loadArtists() {
    try {
      const data = await api.getArtists();
      setArtists(data);
    } catch (err) {
      console.error("Failed to load artists:", err);
    }
  }

  async function loadGenres() {
    try {
      const data = await api.getGenres();
      setGenres(data);
    } catch (err) {
      console.error("Failed to load genres:", err);
    }
  }

  useEffect(() => {
    loadAlbums();
    loadArtists();
    loadGenres();
  }, []);

  const filtered = albums.filter((a) => {
    const q = query.toLowerCase();
    return (
      a.title.toLowerCase().includes(q) ||
      getArtistName(a).toLowerCase().includes(q) ||
      getGenreNames(a).toLowerCase().includes(q)
    );
  });

  const sorted = [...filtered].sort((a, b) => {
    if (sortBy === "title") return a.title.localeCompare(b.title);
    if (sortBy === "artist") return getArtistName(a).localeCompare(getArtistName(b));
    if (sortBy === "newest")
      return (b.release_date || "").localeCompare(a.release_date || "");
    return 0;
  });

  const totalPages = Math.max(1, Math.ceil(sorted.length / pageSize));
  const safePage = Math.min(page, totalPages);
  const visibleAlbums = sorted.slice((safePage - 1) * pageSize, safePage * pageSize);

  async function onSubmit(e) {
    e.preventDefault();
    if (!form.title) return;

    setSubmitting(true);
    try {
      let coverPath = null;
      if (coverFile) {
        const uploaded = await api.uploadImage(coverFile);
        coverPath = uploaded.path;
      }

      let artistId = form.artistId ? Number(form.artistId) : null;

      if (!artistId && form.newArtist.trim()) {
        const created = await api.addArtist({ name: form.newArtist.trim() });
        artistId = created.id;
        await loadArtists();
      }

      let genreIds = [...form.genreIds];

      if (form.newGenre.trim()) {
        const created = await api.addGenre({ name: form.newGenre.trim() });
        genreIds.push(created.id);
        await loadGenres();
      }

      const album = await api.addAlbum({
        title: form.title,
        type: form.type,
        cover_path: coverPath,
        release_date: form.releaseDate || null,
        artist_id: artistId,
        genre_ids: genreIds,
      });

      setForm({ title: "", type: "album", releaseDate: "", artistId: "", newArtist: "", genreIds: [], newGenre: "" });
      setCoverFile(null);
      await loadAlbums();

      navigate(`/albums/${album.id}/tracks`, {
        state: { artistId, genreIds },
      });
    } catch (err) {
      console.error("Failed to add album:", err);
    }
    setSubmitting(false);
  }

  async function onDelete(id) {
    if (!confirm("Delete this album?")) return;
    try {
      await api.deleteAlbum(id);
      await loadAlbums();
    } catch (err) {
      console.error("Failed to delete album:", err);
    }
  }

  return (
    <section>
      <h2>Manage Albums</h2>

      <form className="card form" onSubmit={onSubmit}>
        <h3>Filters</h3>
        <div className="grid">
          <input
            placeholder="Search (title, artist, genre)"
            value={query}
            onChange={(e) => { setQuery(e.target.value); setPage(1); }}
          />
          <select value={sortBy} onChange={(e) => setSortBy(e.target.value)}>
            <option value="newest">Newest</option>
            <option value="title">Title (A-Z)</option>
            <option value="artist">Artist (A-Z)</option>
          </select>
        </div>
        <h3>Add Album</h3>
        <div className="grid">
          <input
            placeholder="Title *"
            value={form.title}
            onChange={(e) => setForm({ ...form, title: e.target.value })}
          />
          <select
            value={form.type}
            onChange={(e) => setForm({ ...form, type: e.target.value })}
          >
            <option value="album">Album</option>
            <option value="single">Single</option>
            <option value="ep">EP</option>
          </select>
          <input
            type="date"
            value={form.releaseDate}
            onChange={(e) => setForm({ ...form, releaseDate: e.target.value })}
          />
        </div>

        <div className="grid">
          <select
            value={form.artistId}
            onChange={(e) => setForm({ ...form, artistId: e.target.value, newArtist: "" })}
          >
            <option value="">Select existing artist...</option>
            {artists.map((a) => (
              <option key={a.id} value={a.id}>{a.name}</option>
            ))}
          </select>
          <input
            placeholder="...or type a new artist name"
            value={form.newArtist}
            onChange={(e) => setForm({ ...form, newArtist: e.target.value, artistId: "" })}
            disabled={!!form.artistId}
          />
        </div>

        <div className="grid">
          <select
            multiple
            value={form.genreIds}
            onChange={(e) =>
              setForm({
                ...form,
                genreIds: Array.from(e.target.selectedOptions, (o) => o.value),
              })
            }
          >
            {genres.map((g) => (
              <option key={g.id} value={g.id}>{g.name}</option>
            ))}
          </select>
          <input
            placeholder="...or type a new genre"
            value={form.newGenre}
            onChange={(e) => setForm({ ...form, newGenre: e.target.value })}
          />
        </div>

        <label className="fileLabel">
          Cover image
          <input type="file" accept="image/*" onChange={(e) => setCoverFile(e.target.files?.[0] || null)} />
        </label>

        <button className="btn primary" type="submit" disabled={submitting}>
          {submitting ? "Adding..." : "Add Album"}
        </button>
      </form>

      <div className="list">
        {loading ? (
          <p>Loading...</p>
        ) : albums.length === 0 ? (
          <p>No albums yet.</p>
        ) : (
          visibleAlbums.map((album) => (
            <div className="card row" key={album.id}>
              <div className="albumInfo">
                {album.cover_path ? (
                  <img className="coverThumb" src={`${API_BASE}/storage/${album.cover_path}`} alt={`${album.title} cover`} />
                ) : (
                  <div className="coverThumb placeholder">No cover</div>
                )}

                <div>
                  <strong>{album.title}</strong> — {getArtistName(album)}
                  <div className="muted">
                    {album.release_date
                      ? new Date(album.release_date).getFullYear()
                      : "Unknown year"}{" "}
                    · {getGenreNames(album)} · {album.type || "album"}
                  </div>
                  <div className="muted">{album.tracks?.length || 0} track(s)</div>
                </div>
              </div>

              <div className="actions">
                <Link className="btn" to={`/albums/${album.id}/tracks`}>
                  Edit
                </Link>
                <button className="btn danger" onClick={() => onDelete(album.id)}>
                  Delete
                </button>
              </div>
            </div>
          ))
        )}
      </div>
      <div className="actions" style={{ marginTop: 10, alignItems: "center" }}>
        <button
          className="btn secondary"
          disabled={safePage <= 1}
          onClick={() => setPage((p) => p - 1)}
        >
          Previous
        </button>
        <span className="muted">
          Page {safePage} / {totalPages}
        </span>
        <button
          className="btn secondary"
          disabled={safePage >= totalPages}
          onClick={() => setPage((p) => p + 1)}
        >
          Next
        </button>
      </div>
    </section>
  );
}
