<template>
  <div
    class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border dark:border-gray-700 overflow-hidden">
    <!-- Mobile Header with Toggle -->
    <div class="lg:hidden">
      <button
        @click="showFilters = !showFilters"
        class="w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors"
      >
        <span class="font-medium text-gray-900 dark:text-white">Filters</span>
        <div class="flex items-center space-x-2">
          <span class="text-sm text-gray-500">{{ articleCount }} articles</span>
          <svg
            :class="{ 'rotate-180': showFilters }"
            class="w-5 h-5 text-gray-400 transition-transform"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M19 9l-7 7-7-7"/>
          </svg>
        </div>
      </button>
    </div>

    <!-- Desktop Header -->
    <div class="hidden lg:block px-6 py-4 border-b dark:border-gray-700">
      <div class="flex items-center justify-between">
        <h3 class="text-lg font-medium text-gray-900 dark:text-white">News Filters</h3>
        <span class="text-sm text-gray-500">{{ articleCount }} articles found</span>
      </div>
    </div>

    <!-- Filters Content -->
    <div
      :class="{ 'hidden': !showFilters }"
      class="lg:block p-4 lg:p-6"
    >
      <!-- Mobile/Tablet: Stacked Layout -->
      <div class="lg:hidden space-y-6">
        <!-- Country Filter Mobile -->
        <div class="bg-gray-50 dark:bg-gray-800 dark:text-gray-200 rounded-lg p-4">
          <h4 class="font-medium text-gray-900 dark:text-white mb-3">Countries</h4>
          <div class="space-y-3 ">
            <label class="flex items-center">
              <input
                type="checkbox"
                v-model="filters.allCountries"
                @change="onAllCountriesChange"
                class="rounded border-gray-300 text-green-600 focus:ring-green-500"
              />
              <span class="ml-3 text-sm dark:text-gray-200">All Countries</span>
            </label>
            <div v-if="!filters.allCountries" class="grid grid-cols-2 gap-2 pl-6">
              <label v-for="country in availableCountries" :key="country" class="flex items-center">
                <input
                  type="checkbox"
                  :value="country"
                  v-model="filters.selectedCountries"
                  class="rounded border-gray-300 text-green-600 focus:ring-green-500"
                />
                <span class="ml-2 text-sm">{{ country }}</span>
              </label>
            </div>
          </div>
        </div>

        <!-- Date Filter Mobile -->
        <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
          <h4 class="font-medium text-gray-900 dark:text-white mb-3">Date Range</h4>
          <div class="space-y-3">
            <label class="flex items-center">
              <input
                type="checkbox"
                v-model="filters.allDates"
                @change="onAllDatesChange"
                class="rounded border-gray-300 text-green-600 focus:ring-green-500"
              />
              <span class="ml-3 text-sm font-medium dark:text-gray-200">All Dates</span>
            </label>
            <div v-if="!filters.allDates" class="space-y-3 pl-6">
              <div class="grid grid-cols-2 gap-3">
                <div>
                  <label class="block text-xs font-medium text-gray-700 dark:text-gray-200 mb-1">From</label>
                  <input
                    type="date"
                    v-model="filters.fromDate"
                    :lang="dateLocale"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:ring-green-500 focus:border-green-500 dark:text-gray-200"
                  />
                </div>
                <div>
                  <label class="block text-xs font-medium text-gray-700 mb-1">To</label>
                  <input
                    type="date"
                    v-model="filters.toDate"
                    :lang="dateLocale"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:ring-green-500 focus:border-green-500 dark:text-gray-200"
                  />
                </div>
              </div>

              <!-- Quick Presets Mobile -->
              <div>
                <h4 class="font-medium text-gray-900 dark:text-white mb-3">Quick Presets</h4>
                <div class="grid grid-cols-2 gap-2">
                  <button
                    v-for="preset in datePresets"
                    :key="preset.label"
                    @click="applyDatePreset(preset)"
                    class="px-3 py-2 text-sm text-green-600 bg-green-50 hover:bg-green-100 dark:hover:bg-green-700 rounded-md transition-colors"
                  >
                    {{ preset.label }}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Action Buttons Mobile -->
        <div class="flex space-x-3">
          <button
            @click="applyFilters"
            :disabled="isLoading"
            class="flex-1 px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium transition-colors"
          >
            <span v-if="isLoading" class="flex items-center justify-center">
              <svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" 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>
              Loading...
            </span>
            <span v-else>Apply Filters</span>
          </button>

          <button
            @click="resetFilters"
            class="px-4 py-3 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 font-medium transition-colors"
          >
            Reset
          </button>
        </div>
      </div>

      <!-- Desktop: Grid Layout -->
      <div class="hidden lg:grid lg:grid-cols-4 gap-6">
        <!-- Country Filter Desktop -->
        <div>
          <label
            class="block text-sm font-medium text-gray-700 dark:text-white mb-3">Countries</label>
          <div class="space-y-2">
            <label class="flex items-center">
              <input
                type="checkbox"
                v-model="filters.allCountries"
                @change="onAllCountriesChange"
                class="rounded border-gray-300 text-green-600 focus:ring-green-500"
              />
              <span class="ml-2 text-sm font-medium dark:text-white">All Countries</span>
            </label>
            <div v-if="!filters.allCountries" class="space-y-1 max-h-40 overflow-y-auto">
              <label v-for="country in availableCountries" :key="country" class="flex items-center">
                <input
                  type="checkbox"
                  :value="country"
                  v-model="filters.selectedCountries"
                  class="rounded border-gray-300 text-green-600 focus:ring-green-500"
                />
                <span class="ml-2 text-sm dark:text-gray-200">{{ country }}</span>
              </label>
            </div>
          </div>
        </div>

        <!-- Date Range Filter Desktop -->
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-white mb-3">Date
            Range</label>
          <div class="space-y-2">
            <label class="flex items-center">
              <input
                type="checkbox"
                v-model="filters.allDates"
                @change="onAllDatesChange"
                class="rounded border-gray-300 text-green-600 focus:ring-green-500"
              />
              <span class="ml-2 text-sm font-medium dark:text-white">All Dates</span>
            </label>
            <div v-if="!filters.allDates" class="space-y-2">
              <div>
                <label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">From</label>
                <input
                  type="date"
                  v-model="filters.fromDate"
                  :lang="dateLocale"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:ring-green-500 focus:border-green-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                />
              </div>
              <div>
                <label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">To</label>
                <input
                  type="date"
                  v-model="filters.toDate"
                  :lang="dateLocale"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:ring-green-500 focus:border-green-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- Quick Date Presets Desktop -->
        <div v-if="!filters.allDates">
          <label class="block text-sm font-medium text-gray-700 dark:text-white mb-3">Quick
            Presets</label>
          <div class="space-y-1">
            <button
              v-for="preset in datePresets"
              :key="preset.label"
              @click="applyDatePreset(preset)"
              class="block w-full text-left px-3 py-2 text-sm text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-900 rounded-md transition-colors"
            >
              {{ preset.label }}
            </button>
          </div>
        </div>

        <!-- Action Buttons Desktop -->
        <div class="flex flex-col space-y-3">
          <button
            @click="applyFilters"
            :disabled="isLoading"
            class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:bg-gray-400 dark:disabled:bg-gray-600 disabled:cursor-not-allowed font-medium transition-colors"
          >
            <span v-if="isLoading" class="flex items-center justify-center">
              <svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" 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>
              Loading...
            </span>
            <span v-else>Apply Filters</span>
          </button>

          <button
            @click="resetFilters"
            class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 font-medium transition-colors"
          >
            Reset
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, ref} from 'vue';
import {useNews} from '../stores/useNews';
import {useFeeds} from '../stores/useFeeds';

const news = useNews();
const feeds = useFeeds();

const dateLocale = computed(() => news.clientLocale || 'en-US');

const isLoading = ref(false);
const showFilters = ref(false);

interface DatePreset {
  label: string;
  fromDate: string;
  toDate: string;
}

const filters = ref({
  allCountries: false,
  selectedCountries: ['DE'] as string[],
  allDates: false,
  fromDate: '',
  toDate: ''
});

// Get available countries from feeds
const availableCountries = computed(() => {
  const countries = new Set(feeds.list.map(feed => feed.country));
  return Array.from(countries).sort();
});

const articleCount = computed(() => news.allArticles.length);

// Date presets
const datePresets: DatePreset[] = [
  {
    label: 'Today',
    fromDate: new Date().toISOString().split('T')[0],
    toDate: new Date().toISOString().split('T')[0]
  },
  {
    label: '3 days',
    fromDate: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    toDate: new Date().toISOString().split('T')[0]
  },
  {
    label: 'Week',
    fromDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    toDate: new Date().toISOString().split('T')[0]
  },
  {
    label: 'Month',
    fromDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    toDate: new Date().toISOString().split('T')[0]
  }
];

// Initialize default dates
onMounted(async () => {
  // Set default date range (last 7 days)
  filters.value.toDate = new Date().toISOString().split('T')[0];
  filters.value.fromDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];

  // Load feeds to get available countries
  await feeds.loadFeeds();

  // Load initial news
  await applyFilters();
});

function onAllCountriesChange() {
  if (filters.value.allCountries) {
    filters.value.selectedCountries = [];
  } else {
    filters.value.selectedCountries = ['DE']; // Default to DE
  }
}

function onAllDatesChange() {
  if (filters.value.allDates) {
    filters.value.fromDate = '';
    filters.value.toDate = '';
  } else {
    // Reset to last week
    filters.value.toDate = new Date().toISOString().split('T')[0];
    filters.value.fromDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
  }
}

function applyDatePreset(preset: DatePreset) {
  filters.value.fromDate = preset.fromDate;
  filters.value.toDate = preset.toDate;
}

async function applyFilters() {
  isLoading.value = true;

  // Auto-close mobile filters after applying
  if (window.innerWidth < 1024) {
    showFilters.value = false;
  }

  try {
    const queryParams: Record<string, string | boolean> = {};

    // Handle countries
    if (filters.value.allCountries) {
      queryParams.all_countries = true;
    } else if (filters.value.selectedCountries.length > 0) {
      queryParams.country = filters.value.selectedCountries.join(',');
    }

    // Handle dates
    if (filters.value.allDates) {
      queryParams.all_dates = true;
    } else {
      if (filters.value.fromDate) {
        queryParams.from_ = filters.value.fromDate;
      }
      if (filters.value.toDate) {
        queryParams.to_ = filters.value.toDate;
      }
    }

    await news.getNews(queryParams);
  } catch (error) {
    console.error('Failed to apply filters:', error);
  } finally {
    isLoading.value = false;
  }
}

function resetFilters() {
  filters.value = {
    allCountries: false,
    selectedCountries: ['DE'],
    allDates: false,
    fromDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    toDate: new Date().toISOString().split('T')[0]
  };
  applyFilters();
}
</script>
