<template>
  <div
    class="flex flex-col sm:flex-row justify-between w-full lg:w-auto gap-2 p-2 bg-white shadow dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-600"
    :class="{ 'opacity-50': props.source.status }"
  >
    <div class="flex-1 flex gap-2 min-w-0">
      <input
        :value="props.source.url"
        type="text"
        placeholder="URL источника"
        :id="'source-url-' + props.source.url"
        :name="'source_url_' + props.source.url"
        readonly
        class="flex-1 sm:mr-1 h-12 dark:bg-gray-900 border-slate-100 shadow rounded-xl p-3 min-w-0"
      />
      <input
        :value="props.source.promt"
        type="text"
        placeholder="Промт"
        :id="'source-promt-' + props.source.url"
        :name="'source_promt_' + props.source.url"
        readonly
        class="h-12 dark:bg-gray-900 border-slate-100 shadow rounded-xl p-3 w-1/3 sm:max-w-20"
      />
    </div>
    <div class="min-w-40 flex gap-1">
      <button
        type="button"
        @click="deleteParsing"
        :disabled="isDeleting"
        class="w-1/3 sm:w-9 h-11 bg-rose-600 hover:bg-rose-800 shadow text-white rounded-xl cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
      >
        ×
      </button>
      <button
        type="button"
        @click="startParsing"
        :disabled="isLoading"
        class="w-2/3 sm:w-25 h-11 dark:bg-orange-500 hover:dark:bg-orange-600 shadow text-white bg-sky-700 hover:bg-sky-900 rounded-xl px-2 cursor-pointer whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed"
      >
        {{ isLoading ? '...' : 'Start' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { startSourceParsing, deleteSource } from '@/services/sourceService.js'

const props = defineProps({
  source: {
    type: Object,
    required: true,
    default: () => ({ url: '', promt: '', status: false }),
  },
})

const emit = defineEmits(['sourceStarted', 'sourceDeleted'])

const isLoading = ref(false)
const isDeleting = ref(false)

async function startParsing() {
  if (!props.source.url) return

  isLoading.value = true
  try {
    await startSourceParsing(props.source.url, props.source.promt)
    emit('sourceStarted', props.source.url)
  } catch (err) {
    console.error('Ошибка запуска парсинга:', err)
    alert('Ошибка при запуске парсинга')
  } finally {
    isLoading.value = false
  }
}

async function deleteParsing() {
  isDeleting.value = true
  try {
    await deleteSource(props.source.url)
    emit('sourceDeleted', props.source.url)
  } catch (error) {
    console.error('Ошибка при удалении источника:', error)
  } finally {
    isDeleting.value = false
  }
}
</script>
