<template>
  <div>
    <div class="pb-5 border-b border-gray-200 sm:flex sm:items-center sm:justify-between">
      <h3 class="text-lg leading-6 font-medium text-gray-900">
        Content Uploads
      </h3>
      <div class="mt-3 sm:mt-0 sm:ml-4">
        <button
          @click="openUploadModal"
          class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
        >
          <svg class="-ml-1 mr-2 h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
          </svg>
          New Upload
        </button>
      </div>
    </div>

    <div class="mt-6">
      <div v-if="loading" class="flex justify-center">
        <svg class="animate-spin -ml-1 mr-3 h-10 w-10 text-primary-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
      </div>
      <div v-else>
        <!-- Filter Controls -->
        <div class="bg-white shadow px-4 py-5 sm:rounded-lg sm:p-6 mb-6">
          <div class="md:flex md:items-center md:justify-between">
            <div class="flex-1 min-w-0">
              <h2 class="text-lg leading-6 font-medium text-gray-900">Filter Uploads</h2>
            </div>
            <div class="mt-4 flex md:mt-0 md:ml-4">
              <div class="flex space-x-3">
                <select
                  v-model="filters.platform"
                  class="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-md"
                >
                  <option value="all">All Platforms</option>
                  <option value="TikTok">TikTok</option>
                  <option value="YouTube">YouTube</option>
                  <option value="Instagram">Instagram</option>
                </select>
                <select
                  v-model="filters.status"
                  class="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-md"
                >
                  <option value="all">All Statuses</option>
                  <option value="draft">Draft</option>
                  <option value="scheduled">Scheduled</option>
                  <option value="published">Published</option>
                </select>
                <button
                  @click="applyFilters"
                  class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
                >
                  Apply Filters
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Uploads List -->
        <div class="bg-white shadow overflow-hidden sm:rounded-md">
          <ul class="divide-y divide-gray-200">
            <li v-if="filteredUploads.length === 0" class="px-4 py-4 sm:px-6">
              <p class="text-sm text-gray-500">No uploads found.</p>
            </li>
            <li v-for="upload in filteredUploads" :key="upload.id" class="px-4 py-4 sm:px-6">
              <div class="flex items-center justify-between">
                <div class="flex items-center">
                  <div class="flex-shrink-0 h-16 w-16 bg-gray-200 rounded"></div>
                  <div class="ml-4">
                    <div class="text-sm font-medium text-gray-900">
                      {{ upload.title }}
                    </div>
                    <div class="text-sm text-gray-500 mt-1">
                      <span class="mr-2">{{ formatDate(upload.uploadDate) }}</span>
                      <span :class="[
                        upload.platform === 'TikTok' ? 'bg-blue-100 text-blue-800' : 
                        upload.platform === 'YouTube' ? 'bg-red-100 text-red-800' : 
                        'bg-pink-100 text-pink-800',
                        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium mr-2'
                      ]">
                        {{ upload.platform }}
                      </span>
                      <span :class="[
                        upload.status === 'draft' ? 'bg-gray-100 text-gray-800' : 
                        upload.status === 'scheduled' ? 'bg-yellow-100 text-yellow-800' : 
                        'bg-green-100 text-green-800',
                        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium'
                      ]">
                        {{ upload.status.charAt(0).toUpperCase() + upload.status.slice(1) }}
                      </span>
                    </div>
                  </div>
                </div>
                <div class="flex space-x-2">
                  <button
                    @click="editUpload(upload)"
                    class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-primary-700 bg-primary-100 hover:bg-primary-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
                  >
                    Edit
                  </button>
                  <button
                    @click="deleteUpload(upload)"
                    class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-red-700 bg-red-100 hover:bg-red-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
                  >
                    Delete
                  </button>
                </div>
              </div>
              <div class="mt-2">
                <p class="text-sm text-gray-500 line-clamp-2">
                  {{ upload.description }}
                </p>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <!-- Upload Modal -->
    <div v-if="showUploadModal" class="fixed z-10 inset-0 overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
      <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true" @click="closeUploadModal"></div>

        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>

        <div class="inline-block align-bottom bg-white rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full sm:p-6">
          <div class="sm:flex sm:items-start">
            <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
              <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">
                {{ editingUpload ? 'Edit Upload' : 'New Upload' }}
              </h3>
              <div class="mt-4">
                <form @submit.prevent="saveUpload">
                  <div class="space-y-4">
                    <div>
                      <label for="title" class="block text-sm font-medium text-gray-700">Title</label>
                      <input
                        type="text"
                        name="title"
                        id="title"
                        v-model="uploadForm.title"
                        class="mt-1 focus:ring-primary-500 focus:border-primary-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md"
                        placeholder="Enter upload title"
                      />
                    </div>

                    <div>
                      <label for="platform" class="block text-sm font-medium text-gray-700">Platform</label>
                      <select
                        id="platform"
                        name="platform"
                        v-model="uploadForm.platform"
                        class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-md"
                      >
                        <option value="TikTok">TikTok</option>
                        <option value="YouTube">YouTube</option>
                        <option value="Instagram">Instagram</option>
                      </select>
                    </div>

                    <div>
                      <label for="upload-date" class="block text-sm font-medium text-gray-700">Upload Date</label>
                      <input
                        type="datetime-local"
                        name="upload-date"
                        id="upload-date"
                        v-model="uploadForm.uploadDate"
                        class="mt-1 focus:ring-primary-500 focus:border-primary-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md"
                      />
                    </div>

                    <div>
                      <label for="status" class="block text-sm font-medium text-gray-700">Status</label>
                      <select
                        id="status"
                        name="status"
                        v-model="uploadForm.status"
                        class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-md"
                      >
                        <option value="draft">Draft</option>
                        <option value="scheduled">Scheduled</option>
                        <option value="published">Published</option>
                      </select>
                    </div>

                    <div>
                      <label for="description" class="block text-sm font-medium text-gray-700">Description</label>
                      <textarea
                        id="description"
                        name="description"
                        rows="3"
                        v-model="uploadForm.description"
                        class="mt-1 focus:ring-primary-500 focus:border-primary-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md"
                        placeholder="Enter upload description"
                      ></textarea>
                    </div>

                    <div>
                      <label for="hashtags" class="block text-sm font-medium text-gray-700">Hashtags</label>
                      <input
                        type="text"
                        name="hashtags"
                        id="hashtags"
                        v-model="uploadForm.hashtags"
                        class="mt-1 focus:ring-primary-500 focus:border-primary-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md"
                        placeholder="Enter hashtags separated by spaces"
                      />
                    </div>
                  </div>

                  <div class="mt-5 sm:mt-6 sm:grid sm:grid-cols-2 sm:gap-3 sm:grid-flow-row-dense">
                    <button
                      type="submit"
                      class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-primary-600 text-base font-medium text-white hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 sm:col-start-2 sm:text-sm"
                    >
                      {{ editingUpload ? 'Save Changes' : 'Create Upload' }}
                    </button>
                    <button
                      type="button"
                      @click="closeUploadModal"
                      class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 sm:mt-0 sm:col-start-1 sm:text-sm"
                    >
                      Cancel
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';

export default {
  name: 'Uploads',
  setup() {
    const loading = ref(true);
    const uploads = ref([]);
    const showUploadModal = ref(false);
    const editingUpload = ref(false);
    const currentUploadId = ref(null);
    
    const filters = ref({
      platform: 'all',
      status: 'all'
    });
    
    const uploadForm = ref({
      title: '',
      platform: 'TikTok',
      uploadDate: '',
      status: 'draft',
      description: '',
      hashtags: ''
    });
    
    const filteredUploads = computed(() => {
      let result = [...uploads.value];
      
      if (filters.value.platform !== 'all') {
        result = result.filter(upload => upload.platform === filters.value.platform);
      }
      
      if (filters.value.status !== 'all') {
        result = result.filter(upload => upload.status === filters.value.status);
      }
      
      return result;
    });
    
    const fetchUploads = async () => {
      loading.value = true;
      try {
        // In a real app, this would be an API call
        // const response = await axios.get('/api/uploads');
        // uploads.value = response.data;
        
        // For demo purposes, we'll use mock data
        setTimeout(() => {
          uploads.value = [
            {
              id: 1,
              title: 'Relaxing Rain Sounds ASMR',
              platform: 'YouTube',
              uploadDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days in the future
              status: 'scheduled',
              description: 'Soothing rain sounds to help you relax and fall asleep. Perfect for meditation and stress relief.',
              hashtags: '#asmr #rainsounds #sleep #relaxation'
            },
            {
              id: 2,
              title: 'Tapping Sounds for Sleep',
              platform: 'TikTok',
              uploadDate: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000), // 2 days in the future
              status: 'scheduled',
              description: 'Gentle tapping sounds to help you fall asleep faster. Great for insomnia relief.',
              hashtags: '#asmr #tapping #sleep #insomnia'
            },
            {
              id: 3,
              title: 'Whisper ASMR Session',
              platform: 'YouTube',
              uploadDate: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000), // 5 days ago
              status: 'published',
              description: 'Soft whispers to trigger your ASMR and help you relax. Close your eyes and enjoy.',
              hashtags: '#asmr #whisper #relaxation #tingles'
            },
            {
              id: 4,
              title: 'Calming Sounds for Anxiety',
              platform: 'Instagram',
              uploadDate: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000), // 10 days ago
              status: 'published',
              description: 'A collection of calming sounds designed to reduce anxiety and promote relaxation.',
              hashtags: '#asmr #anxiety #calm #mentalhealth'
            },
            {
              id: 5,
              title: 'Sleep-Inducing ASMR',
              platform: 'TikTok',
              uploadDate: null,
              status: 'draft',
              description: 'Work in progress: A mix of the most effective sleep-inducing ASMR triggers.',
              hashtags: '#asmr #sleep #relaxation #tingles'
            }
          ];
          
          loading.value = false;
        }, 1000);
      } catch (error) {
        console.error('Error fetching uploads:', error);
        loading.value = false;
      }
    };
    
    const openUploadModal = () => {
      resetUploadForm();
      editingUpload.value = false;
      currentUploadId.value = null;
      showUploadModal.value = true;
    };
    
    const closeUploadModal = () => {
      showUploadModal.value = false;
    };
    
    const resetUploadForm = () => {
      uploadForm.value = {
        title: '',
        platform: 'TikTok',
        uploadDate: formatDateForInput(new Date()),
        status: 'draft',
        description: '',
        hashtags: ''
      };
    };
    
    const editUpload = (upload) => {
      editingUpload.value = true;
      currentUploadId.value = upload.id;
      
      uploadForm.value = {
        title: upload.title,
        platform: upload.platform,
        uploadDate: upload.uploadDate ? formatDateForInput(new Date(upload.uploadDate)) : '',
        status: upload.status,
        description: upload.description,
        hashtags: upload.hashtags
      };
      
      showUploadModal.value = true;
    };
    
    const saveUpload = async () => {
      try {
        if (editingUpload.value) {
          // In a real app, this would be an API call
          // await axios.put(`/api/uploads/${currentUploadId.value}`, uploadForm.value);
          
          // For demo purposes, we'll just update the local array
          const index = uploads.value.findIndex(u => u.id === currentUploadId.value);
          if (index !== -1) {
            uploads.value[index] = {
              ...uploads.value[index],
              ...uploadForm.value,
              uploadDate: uploadForm.value.uploadDate ? new Date(uploadForm.value.uploadDate) : null
            };
          }
        } else {
          // In a real app, this would be an API call
          // const response = await axios.post('/api/uploads', uploadForm.value);
          // const newUpload = response.data;
          
          // For demo purposes, we'll just add to the local array
          const newUpload = {
            id: Math.max(0, ...uploads.value.map(u => u.id)) + 1,
            ...uploadForm.value,
            uploadDate: uploadForm.value.uploadDate ? new Date(uploadForm.value.uploadDate) : null
          };
          
          uploads.value.push(newUpload);
        }
        
        closeUploadModal();
      } catch (error) {
        console.error('Error saving upload:', error);
        alert('Failed to save upload. Please try again.');
      }
    };
    
    const deleteUpload = async (upload) => {
      if (!confirm(`Are you sure you want to delete "${upload.title}"?`)) return;
      
      try {
        // In a real app, this would be an API call
        // await axios.delete(`/api/uploads/${upload.id}`);
        
        // For demo purposes, we'll just remove from the local array
        uploads.value = uploads.value.filter(u => u.id !== upload.id);
      } catch (error) {
        console.error('Error deleting upload:', error);
        alert('Failed to delete upload. Please try again.');
      }
    };
    
    const applyFilters = () => {
      // In a real app, this might trigger a new API call with filter parameters
      console.log('Applying filters:', filters.value);
    };
    
    const formatDate = (date) => {
      if (!date) return 'Not scheduled';
      
      const d = new Date(date);
      return d.toLocaleDateString('en-US', {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    };
    
    const formatDateForInput = (date) => {
      if (!date) return '';
      
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      
      return `${year}-${month}-${day}T${hours}:${minutes}`;
    };
    
    onMounted(() => {
      fetchUploads();
    });
    
    return {
      loading,
      uploads,
      filteredUploads,
      showUploadModal,
      editingUpload,
      filters,
      uploadForm,
      openUploadModal,
      closeUploadModal,
      editUpload,
      saveUpload,
      deleteUpload,
      applyFilters,
      formatDate
    };
  }
};
</script> 