<template>
  <div class="min-h-screen bg-noctune-cream flex flex-col">
    <div class="flex flex-1">
      <main class="flex-1 p-8 overflow-auto">
        <div class="max-w-2xl mx-auto">
          <h1 class="text-4xl font-black text-black mb-2">Upload Track</h1>
          <p class="text-gray-600 mb-8">Add a new track to the library</p>
          <p v-if="error" class="text-red-500 text-sm mb-4 font-medium">
            {{ error }}
          </p>
          <p v-if="success" class="text-green-600 text-sm mb-4 font-medium">
            {{ success }}
          </p>
          <div class="bg-white rounded-2xl border-4 border-black p-8 space-y-6">
            <div>
              <label
                class="block text-xs font-bold text-gray-600 mb-2 tracking-wider"
                >TITLE</label
              >
              <input
                type="text"
                v-model="title"
                class="w-full border-2 border-black rounded-lg px-4 py-3 focus:outline-none text-black"
                placeholder="Track title"
              />
            </div>
            <div>
              <label
                class="block text-xs font-bold text-gray-600 mb-2 tracking-wider"
                >ARTIST</label
              >
              <input
                type="text"
                v-model="artist"
                class="w-full border-2 border-black rounded-lg px-4 py-3 focus:outline-none text-black"
                placeholder="Artist name"
              />
            </div>
            <div>
              <label
                class="block text-xs font-bold text-gray-600 mb-2 tracking-wider"
                >ALBUM</label
              >
              <input
                type="text"
                v-model="album"
                class="w-full border-2 border-black rounded-lg px-4 py-3 focus:outline-none text-black"
                placeholder="Album name"
              />
            </div>
            <div>
              <label
                class="block text-xs font-bold text-gray-600 mb-2 tracking-wider"
                >GENRE</label
              >
              <input
                type="text"
                v-model="genre"
                class="w-full border-2 border-black rounded-lg px-4 py-3 focus:outline-none text-black"
                placeholder="e.g. Pop, Rock, Jazz"
              />
            </div>
            <div>
              <label
                class="block text-xs font-bold text-gray-600 mb-2 tracking-wider"
                >COVER IMAGE</label
              >
              <div
                class="border-2 border-dashed border-black rounded-lg p-6 text-center cursor-pointer hover:bg-gray-50"
                @click="coverInput.click()"
              >
                <img
                  v-if="coverPreview"
                  :src="coverPreview"
                  class="w-32 h-32 object-cover mx-auto mb-2 rounded-lg border-2 border-black"
                />
                <p v-else class="text-gray-500">Click to upload cover image</p>
                <input
                  ref="coverInput"
                  type="file"
                  accept="image/*"
                  @change="onCoverChange"
                  class="hidden"
                />
              </div>
            </div>
            <div>
              <label
                class="block text-xs font-bold text-gray-600 mb-2 tracking-wider"
                >AUDIO FILE</label
              >
              <div
                class="border-2 border-dashed border-black rounded-lg p-6 text-center cursor-pointer hover:bg-gray-50"
                @click="audioInput.click()"
              >
                <p v-if="audioFile" class="text-black font-medium">
                  {{ audioFile.name }}
                </p>
                <p v-else class="text-gray-500">
                  Click to upload audio file (MP3, WAV, FLAC)
                </p>
                <input
                  ref="audioInput"
                  type="file"
                  accept=".mp3,.wav,.flac"
                  @change="onAudioChange"
                  class="hidden"
                />
              </div>
            </div>
            <button
              @click="handleUpload"
              :disabled="uploading"
              class="w-full bg-noctune-orange border-2 border-black rounded-lg py-4 font-bold text-white text-xl hover:bg-orange-600 transition-colors disabled:opacity-50"
            >
              <span
                v-if="uploading"
                class="inline-block w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"
              ></span>
              {{ uploading ? 'Uploading...' : 'UPLOAD TRACK' }}
            </button>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import AppHeader from '../components/AppHeader.vue';
import Sidebar from '../components/Sidebar.vue';
import api from '../lib/api.js';

const router = useRouter();

const title = ref('');
const artist = ref('');
const album = ref('');
const genre = ref('');
const coverFile = ref(null);
const coverPreview = ref('');
const audioFile = ref(null);
const uploading = ref(false);
const error = ref('');
const success = ref('');

const coverInput = ref(null);
const audioInput = ref(null);

function onCoverChange(e) {
  const file = e.target.files[0];
  if (!file) return;
  coverFile.value = file;
  coverPreview.value = URL.createObjectURL(file);
}

function onAudioChange(e) {
  const file = e.target.files[0];
  if (!file) return;
  audioFile.value = file;
}

async function handleUpload() {
  error.value = '';
  success.value = '';

  if (
    !title.value ||
    !artist.value ||
    !album.value ||
    !genre.value ||
    !coverFile.value ||
    !audioFile.value
  ) {
    error.value = 'All fields are required';
    return;
  }

  uploading.value = true;
  try {
    const formData = new FormData();
    formData.append('title', title.value);
    formData.append('artist', artist.value);
    formData.append('album', album.value);
    formData.append('genre', genre.value);
    formData.append('cover', coverFile.value);
    formData.append('audio', audioFile.value);

    const { data } = await api.post('/admin/tracks', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });

    if (data.success) {
      success.value = 'Track uploaded successfully!';
      title.value = '';
      artist.value = '';
      album.value = '';
      genre.value = '';
      coverFile.value = null;
      coverPreview.value = '';
      audioFile.value = null;
      setTimeout(() => router.push('/home'), 1500);
    }
  } catch (err) {
    error.value = err.response?.data?.message || 'Upload failed';
  } finally {
    uploading.value = false;
  }
}
</script>
