<template>
  <div class="p-6">
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-800">Restaurant Settings</h1>
      <p class="text-gray-600">Manage your restaurant information</p>
    </div>

    <div v-if="loading" class="bg-white rounded-xl shadow-sm p-8 text-center">
      <div class="animate-spin h-8 w-8 border-4 border-orange-500 border-t-transparent rounded-full mx-auto"></div>
    </div>

    <div v-else class="bg-white rounded-xl shadow-sm p-6">
      <form @submit.prevent="saveSettings" class="space-y-6">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Restaurant Name *</label>
            <input v-model="form.name" type="text" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent">
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Phone *</label>
            <input v-model="form.phone" type="text" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent">
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Email</label>
            <input v-model="form.email" type="email" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent">
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Status</label>
            <select v-model="form.operational_status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent">
              <option value="open">Open</option>
              <option value="closed">Closed</option>
              <option value="busy">Busy</option>
            </select>
          </div>
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">Description</label>
          <textarea v-model="form.description" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent"></textarea>
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">Address *</label>
          <textarea v-model="form.address" rows="2" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent"></textarea>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Minimum Order (Rs)</label>
            <input v-model.number="form.minimum_order" type="number" min="0" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent">
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Delivery Fee per KM (Rs)</label>
            <input v-model.number="form.delivery_fee" type="number" min="0" readonly class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-100 cursor-not-allowed">
            <p class="text-xs text-gray-500 mt-1">Contact admin to change delivery fee</p>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Delivery Radius (km)</label>
            <input v-model.number="form.delivery_radius" type="number" min="0" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent">
          </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Opening Time</label>
            <input v-model="form.opening_time" type="time" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent">
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Closing Time</label>
            <input v-model="form.closing_time" type="time" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent">
          </div>
        </div>

        <!-- Delivery Settings -->
        <div class="border-t pt-6 mt-6">
          <h2 class="text-lg font-bold text-gray-800 mb-4">🚚 Delivery Settings</h2>
          
          <!-- Delivery On/Off Toggle -->
          <div class="bg-gray-50 rounded-lg p-4 mb-6">
            <div class="flex items-center justify-between">
              <div>
                <h3 class="font-semibold text-gray-800">Delivery Service</h3>
                <p class="text-sm text-gray-600">Enable or disable delivery for customers</p>
              </div>
              <button @click="form.delivery_enabled = !form.delivery_enabled" type="button" 
                :class="form.delivery_enabled ? 'bg-green-500' : 'bg-gray-300'" 
                class="relative inline-flex h-8 w-14 items-center rounded-full transition-colors">
                <span :class="form.delivery_enabled ? 'translate-x-7' : 'translate-x-1'" 
                  class="inline-block h-6 w-6 transform rounded-full bg-white transition-transform"></span>
              </button>
            </div>
          </div>

          <!-- Delivery Time Slots -->
          <div v-if="form.delivery_enabled">
            <div class="flex items-center justify-between mb-4">
              <h3 class="font-semibold text-gray-800">Delivery Time Slots</h3>
              <button @click="addTimeSlot" type="button" class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm hover:bg-blue-700">
                + Add Slot
              </button>
            </div>
            
            <div class="space-y-3">
              <div v-for="(slot, index) in form.delivery_slots" :key="index" 
                class="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                <input v-model="slot.start_time" type="time" required 
                  class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500">
                <span class="text-gray-600">to</span>
                <input v-model="slot.end_time" type="time" required 
                  class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500">
                <button @click="removeTimeSlot(index)" type="button" 
                  class="ml-auto p-2 text-red-600 hover:bg-red-50 rounded-lg">
                  🗑️
                </button>
              </div>
            </div>
            
            <p class="text-sm text-gray-500 mt-2">
              💡 Customers can only place orders during these time slots
            </p>
          </div>
        </div>

        <div class="flex gap-4">
          <button type="submit" :disabled="saving" class="bg-orange-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-orange-700 transition disabled:opacity-50">
            {{ saving ? 'Saving...' : 'Save Changes' }}
          </button>
          <button type="button" @click="loadRestaurant" class="bg-gray-200 text-gray-700 px-6 py-3 rounded-lg font-semibold hover:bg-gray-300 transition">
            Cancel
          </button>
        </div>
      </form>
    </div>

    <Toast :show="showToast" :message="toastMessage" :type="toastType" @close="showToast = false" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import api from '../../services/api';
import Toast from '../Toast.vue';

const loading = ref(true);
const saving = ref(false);
const showToast = ref(false);
const toastMessage = ref('');
const toastType = ref('success');
const form = ref({
  name: '',
  phone: '',
  email: '',
  description: '',
  address: '',
  minimum_order: 500,
  delivery_fee: 100,
  delivery_radius: 10,
  opening_time: '09:00',
  closing_time: '22:00',
  operational_status: 'open',
  delivery_enabled: true,
  delivery_slots: [
    { start_time: '09:00', end_time: '12:00' },
    { start_time: '12:00', end_time: '15:00' },
    { start_time: '18:00', end_time: '22:00' }
  ]
});

const loadRestaurant = async () => {
  try {
    loading.value = true;
    const response = await api.get('/manager/restaurant');
    const data = response.data.data || response.data;
    form.value = {
      name: data.name || '',
      phone: data.phone || '',
      email: data.email || '',
      description: data.description || '',
      address: data.address || '',
      minimum_order: data.minimum_order || 500,
      delivery_fee: data.delivery_fee || 100,
      delivery_radius: data.delivery_radius || 10,
      opening_time: data.opening_time || '09:00',
      closing_time: data.closing_time || '22:00',
      operational_status: data.operational_status || 'open',
      delivery_enabled: data.delivery_enabled !== undefined ? data.delivery_enabled : true,
      delivery_slots: data.delivery_slots ? JSON.parse(data.delivery_slots) : [
        { start_time: '09:00', end_time: '12:00' },
        { start_time: '12:00', end_time: '15:00' },
        { start_time: '18:00', end_time: '22:00' }
      ]
    };
  } catch (error) {
    console.error('Error loading restaurant:', error);
    toastMessage.value = 'Failed to load restaurant details';
    toastType.value = 'error';
    showToast.value = true;
  } finally {
    loading.value = false;
  }
};

const saveSettings = async () => {
  try {
    saving.value = true;
    const payload = {
      ...form.value,
      delivery_slots: JSON.stringify(form.value.delivery_slots)
    };
    await api.put('/manager/restaurant', payload);
    toastMessage.value = 'Restaurant settings updated successfully!';
    toastType.value = 'success';
    showToast.value = true;
  } catch (error) {
    console.error('Error saving settings:', error);
    toastMessage.value = error.response?.data?.message || 'Failed to save settings';
    toastType.value = 'error';
    showToast.value = true;
  } finally {
    saving.value = false;
  }
};

const addTimeSlot = () => {
  form.value.delivery_slots.push({ start_time: '09:00', end_time: '12:00' });
};

const removeTimeSlot = (index) => {
  form.value.delivery_slots.splice(index, 1);
};

onMounted(() => {
  loadRestaurant();
});
</script>
