<template>
  <AppLayout>
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-900">Restaurants</h1>
      <button @click="openModal('create')" class="btn-primary flex items-center gap-2">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
        </svg>
        Add Restaurant
      </button>
    </div>

    <div class="card overflow-hidden">
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Host</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">HTTPS</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Login</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Created</th>
              <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-200 bg-white">
            <tr v-for="rest in restaurants" :key="rest.id" class="hover:bg-gray-50 transition-colors">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ rest.id }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ rest.name }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ rest.host }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm">
                <label class="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    :checked="rest.https"
                    @change="toggleHttps(rest)"
                    class="sr-only peer"
                  />
                  <div class="w-9 h-5 bg-gray-200 rounded-full peer peer-checked:bg-primary-600 transition-colors"></div>
                  <div class="absolute left-0.5 top-0.5 w-4 h-4 bg-white rounded-full transition-transform peer-checked:translate-x-4"></div>
                </label>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ rest.login }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ formatDate(rest.created) }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-3">
                <button @click="openModal('edit', rest)" class="text-blue-600 hover:text-blue-800 transition-colors">
                  <svg class="w-5 h-5 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                  </svg>
                </button>
                <button @click="confirmDelete(rest.id)" class="text-red-600 hover:text-red-800 transition-colors">
                  <svg class="w-5 h-5 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                </button>
              </td>
            </tr>
            <tr v-if="restaurants.length === 0">
              <td colspan="7" class="px-6 py-12 text-center text-gray-500">No restaurants found. Click "Add Restaurant" to create one.</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Модалка создания/редактирования ресторана -->
    <Transition name="fade">
      <div v-if="modalOpen" class="fixed inset-0 z-50 overflow-y-auto" @click.self="closeModal">
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm"></div>
        <div class="flex items-center justify-center min-h-screen p-4">
          <div class="relative bg-white rounded-2xl shadow-xl max-w-md w-full transform transition-all">
            <div class="flex justify-between items-center p-6 border-b">
              <h2 class="text-xl font-bold text-gray-900">{{ modalTitle }}</h2>
              <button @click="closeModal" class="text-gray-400 hover:text-gray-600 transition-colors">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            <form @submit.prevent="submitRestaurant" class="p-6 space-y-5">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Name *</label>
                <input v-model="form.name" type="text" required class="input-field" />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Host *</label>
                <input v-model="form.host" type="text" required class="input-field" placeholder="e.g., api.example.com" />
              </div>
              <div class="flex items-center">
                <input type="checkbox" v-model="form.https" class="rounded border-gray-300 text-primary-600 focus:ring-primary-500 w-4 h-4 mr-2" />
                <label class="text-sm font-medium text-gray-700">Use HTTPS</label>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Login *</label>
                <input v-model="form.login" type="text" required class="input-field" />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Password</label>
                <input
                  v-model="form.password"
                  :required="modalMode === 'create'"
                  type="password"
                  class="input-field"
                  autocomplete="new-password"
                />
                <p v-if="modalMode === 'edit'" class="text-xs text-gray-500 mt-1">Leave blank to keep current password</p>
              </div>
              <div class="flex justify-end space-x-3 pt-2">
                <button type="button" @click="closeModal" class="btn-secondary">Cancel</button>
                <button type="submit" class="btn-primary">Save</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </Transition>

    <!-- Модалка подтверждения удаления ресторана -->
    <Transition name="fade">
      <div v-if="deleteConfirm.show" class="fixed inset-0 z-50 overflow-y-auto" @click.self="deleteConfirm.show = false">
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm"></div>
        <div class="flex items-center justify-center min-h-screen p-4">
          <div class="relative bg-white rounded-2xl shadow-xl max-w-md w-full">
            <div class="p-6 text-center">
              <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100 mb-4">
                <svg class="h-6 w-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
              </div>
              <h3 class="text-lg font-medium text-gray-900 mb-2">Delete Restaurant</h3>
              <p class="text-sm text-gray-500 mb-6">Are you sure you want to delete this restaurant? This action cannot be undone.</p>
              <div class="flex justify-center space-x-3">
                <button @click="deleteConfirm.show = false" class="btn-secondary">Cancel</button>
                <button @click="deleteRestaurant(deleteConfirm.id)" class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700 transition-colors">Delete</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </AppLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import AppLayout from '../components/Layout/AppLayout.vue';

const restaurants = ref([]);
const modalOpen = ref(false);
const modalMode = ref<'create' | 'edit'>('create');
const form = ref({ id: null, name: '', login: '', password: '', host: '', https: false });
const modalTitle = ref('');
const deleteConfirm = ref({ show: false, id: null });

async function loadRestaurants() {
  const res = await fetch('/api/admin/restaurants');
  restaurants.value = await res.json();
}

function formatDate(dateStr: string) {
  if (!dateStr) return '-';
  return new Date(dateStr).toLocaleString();
}

function openModal(mode: 'create' | 'edit', rest: any = null) {
  modalMode.value = mode;
  if (mode === 'create') {
    form.value = { id: null, name: '', login: '', password: '', host: '', https: false };
    modalTitle.value = 'Create Restaurant';
  } else {
    form.value = {
      id: rest.id,
      name: rest.name,
      login: rest.login,
      password: '',
      host: rest.host,
      https: rest.https || false
    };
    modalTitle.value = 'Edit Restaurant';
  }
  modalOpen.value = true;
}

function closeModal() {
  modalOpen.value = false;
}

async function toggleHttps(rest: any) {
  const newHttps = !rest.https;
  const payload = {
    name: rest.name,
    host: rest.host,
    login: rest.login,
    https: newHttps
  };
  try {
    const res = await fetch(`/api/admin/restaurants/${rest.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });
    if (res.ok) {
      rest.https = newHttps;
    } else {
      alert('Failed to update HTTPS status');
    }
  } catch (e) {
    alert('Network error');
  }
}

async function submitRestaurant() {
  try {
    const payload = {
      name: form.value.name,
      host: form.value.host,
      https: form.value.https,
      login: form.value.login,
      ...(form.value.password ? { password: form.value.password } : {})
    };
    if (modalMode.value === 'create') {
      if (!form.value.password) {
        alert('Password is required');
        return;
      }
      const res = await fetch('/api/admin/restaurants', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      if (!res.ok) throw new Error('Create failed');
    } else {
      const res = await fetch(`/api/admin/restaurants/${form.value.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      if (!res.ok) throw new Error('Update failed');
    }
    await loadRestaurants();
    closeModal();
  } catch (e) {
    alert('Operation failed: ' + e.message);
  }
}

function confirmDelete(id: number) {
  deleteConfirm.value = { show: true, id };
}

async function deleteRestaurant(id: number) {
  await fetch(`/api/admin/restaurants/${id}`, { method: 'DELETE' });
  await loadRestaurants();
  deleteConfirm.value.show = false;
}

onMounted(loadRestaurants);
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
