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

export default function AlbumsPage() {
    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 [form, setForm] = useState({
        title: "",
        artist: "",
        year: "",
        genre: "",
    });
    const [coverFile, setCoverFile] = useState(null);
    const [audioFiles, setAudioFiles] = useState([]);

    async function loadAlbums() {
        setLoading(true);
        const data = await api.getAlbums();
        setAlbums(data);
        setLoading(false);
    }

    useEffect(() => {
        const data = api.getAlbums();
        setAlbums(data);
        setLoading(false);
    }, []);

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

    const sorted = [...filtered].sort((a, b) => {
        if (sortBy === "title") return a.title.localeCompare(b.title);
        if (sortBy === "artist") return a.artist.localeCompare(b.artist);
        if (sortBy === "year") return (a.year || "").localeCompare(b.year || "");
        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 || !form.artist) return;

        await api.addAlbum({
            ...form,
            cover: coverFile
                ? {
                    name: coverFile.name,
                    url: URL.createObjectURL(coverFile),
                }
                : null,
            tracks: audioFiles.map((f) => ({ name: f.name })),
        });

        setForm({ title: "", artist: "", year: "", genre: "" });
        setCoverFile(null);
        setAudioFiles([]);
        await loadAlbums();
    }

    async function onDelete(id) {
        if (!confirm("Delete this album?")) return;
        await api.deleteAlbum(id);
        await loadAlbums();
    }

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

            <form className="card form" onSubmit={onSubmit}>
                <h3>Filtres</h3>
                <div className="grid">
                    <input
                        placeholder="Rechercher (titre, artiste, genre)"
                        value={query}
                        onChange={(e) => { setQuery(e.target.value); setPage(1); }}
                    />
                    <select value={sortBy} onChange={(e) => setSortBy(e.target.value)}>
                        <option value="newest">Plus récents</option>
                        <option value="title">Titre (A-Z)</option>
                        <option value="artist">Artiste (A-Z)</option>
                        <option value="year">Année</option>
                    </select>
                </div>
                <h3>Add Album</h3>
                <div className="grid">
                    <input
                        placeholder="Title *"
                        value={form.title}
                        onChange={(e) => setForm({ ...form, title: e.target.value })}
                    />
                    <input
                        placeholder="Artist *"
                        value={form.artist}
                        onChange={(e) => setForm({ ...form, artist: e.target.value })}
                    />
                    <input
                        placeholder="Year"
                        value={form.year}
                        onChange={(e) => setForm({ ...form, year: e.target.value })}
                    />
                    <input
                        placeholder="Genre"
                        value={form.genre}
                        onChange={(e) => setForm({ ...form, genre: e.target.value })}
                    />
                </div>

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

                <label className="fileLabel">
                    Audio files (mp3, wav, flac...)
                    <input
                        type="file"
                        multiple
                        accept=".mp3,.wav,.flac,audio/*"
                        onChange={(e) => setAudioFiles(Array.from(e.target.files || []))}
                    />
                </label>

                <button className="btn primary" type="submit">
                    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?.url ? (
                                    <img className="coverThumb" src={album.cover.url} alt={`${album.title} cover`} />
                                ) : (
                                    <div className="coverThumb placeholder">No cover</div>
                                )}

                                <div>
                                    <strong>{album.title}</strong> — {album.artist}
                                    <div className="muted">
                                        {album.year || "Unknown year"} · {album.genre || "No genre"}
                                    </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 tracks
                                </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)}
                >
                    Précédent
                </button>
                <span className="muted">
                    Page {safePage} / {totalPages}
                </span>
                <button
                    className="btn secondary"
                    disabled={safePage >= totalPages}
                    onClick={() => setPage((p) => p + 1)}
                >
                    Suivant
                </button>
            </div>
        </section>
    );
}