<script lang="ts">
  import { flowerPots, type FlowerPot } from '$lib/stores';
  import PlantDetailModal from './PlantDetailModal.svelte';

  let pots: FlowerPot[] = [];
  let view: 'cards' | 'table' = 'cards';
  let selectedPot: FlowerPot | null = null;
  let isModalOpen = false;

  // Notification state
  let notification: { message: string; type: 'success' | 'error' } | null = null;
  let notificationTimeout: number;

  // Watering cooldown (2 hours in milliseconds)
  const WATERING_COOLDOWN = 2 * 60 * 60 * 1000; // 2 hours
  let lastWateringTimes: Map<string, number> = new Map();

  // Load view preference from localStorage
  $: if (typeof localStorage !== 'undefined') {
    const storedView = localStorage.getItem('plant-view-preference');
    if (storedView === 'cards' || storedView === 'table') {
      view = storedView;
    }
  }

  flowerPots.subscribe(value => {
    pots = value;
  });

  function waterPot(id: string) {
    // Check if watering is allowed (not in cooldown)
    if (!canWater(id)) {
      showNotification('Please wait before watering this plant again.', 'error');
      return;
    }

    flowerPots.water(id);
    // Record the watering time for cooldown
    lastWateringTimes.set(id, Date.now());

    const pot = pots.find(p => p.id === id);
    if (pot) {
      showNotification(`Successfully watered ${pot.name}!`, 'success');
    }
  }

  function canWater(potId: string): boolean {
    const lastWatering = lastWateringTimes.get(potId);
    if (!lastWatering) return true;

    const timeSinceLastWatering = Date.now() - lastWatering;
    return timeSinceLastWatering >= WATERING_COOLDOWN;
  }

  function getCooldownTimeRemaining(potId: string): number {
    const lastWatering = lastWateringTimes.get(potId);
    if (!lastWatering) return 0;

    const timeSinceLastWatering = Date.now() - lastWatering;
    const remaining = WATERING_COOLDOWN - timeSinceLastWatering;
    return Math.max(0, remaining);
  }

  function formatCooldownTime(milliseconds: number): string {
    const minutes = Math.ceil(milliseconds / (1000 * 60));
    if (minutes < 60) {
      return `${minutes}m`;
    }
    const hours = Math.floor(minutes / 60);
    const remainingMinutes = minutes % 60;
    return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
  }

  function showNotification(message: string, type: 'success' | 'error' = 'success') {
    notification = { message, type };
    // Clear any existing timeout
    if (notificationTimeout) {
      clearTimeout(notificationTimeout);
    }
    // Auto-hide after 3 seconds
    notificationTimeout = setTimeout(() => {
      notification = null;
    }, 3000);
  }

  function removePot(id: string) {
    if (confirm('Are you sure you want to remove this flower pot?')) {
      flowerPots.remove(id);
    }
  }

  function editPot(pot: FlowerPot) {
    // Dispatch custom event to open edit modal
    const event = new CustomEvent('edit-plant', { detail: pot });
    window.dispatchEvent(event);
  }

  function getStatusColor(pot: FlowerPot): string {
    const now = new Date();
    const timeDiff = pot.nextWatering.getTime() - now.getTime();
    const hoursDiff = timeDiff / (1000 * 60 * 60);

    if (hoursDiff < 0) return 'bg-red-100 border-red-300 text-red-800'; // Overdue
    if (hoursDiff < 24) return 'bg-yellow-100 border-yellow-300 text-yellow-800'; // Due soon
    return 'bg-green-100 border-green-300 text-green-800'; // Good
  }

  function getStatusText(pot: FlowerPot): string {
    const now = new Date();
    const timeDiff = pot.nextWatering.getTime() - now.getTime();
    const hoursDiff = timeDiff / (1000 * 60 * 60);

    if (hoursDiff < 0) return 'Overdue!';
    if (hoursDiff < 24) return `Due in ${Math.ceil(hoursDiff)}h`;
    const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
    return `Due in ${daysDiff}d`;
  }

  function getStatusBadgeClass(pot: FlowerPot): string {
    const now = new Date();
    const timeDiff = pot.nextWatering.getTime() - now.getTime();
    const hoursDiff = timeDiff / (1000 * 60 * 60);

    if (hoursDiff < 0) return 'bg-red-100 text-red-800'; // Overdue
    if (hoursDiff < 24) return 'bg-yellow-100 text-yellow-800'; // Due soon
    return 'bg-green-100 text-green-800'; // Good
  }

  function openPlantDetail(pot: FlowerPot) {
    selectedPot = pot;
    isModalOpen = true;
  }

  function closePlantDetail() {
    isModalOpen = false;
    selectedPot = null;
  }
</script>

{#if pots.length === 0}
  <div class="text-center py-8 text-gray-500 dark:text-gray-400">
    <p class="text-lg mb-2">No flower pots yet</p>
    <p>Add your first pot to get started!</p>
  </div>
{:else}
  <!-- Notification -->
  {#if notification}
    <div class="fixed top-4 right-4 z-50 animate-in slide-in-from-top-2 duration-300">
      <div class="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg p-4 max-w-sm">
        <div class="flex items-center gap-3">
          <div class="flex-shrink-0">
            {#if notification.type === 'success'}
              <div class="w-8 h-8 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center">
                <span class="text-green-600 dark:text-green-400 text-lg">✓</span>
              </div>
            {:else}
              <div class="w-8 h-8 bg-red-100 dark:bg-red-900 rounded-full flex items-center justify-center">
                <span class="text-red-600 dark:text-red-400 text-lg">✕</span>
              </div>
            {/if}
          </div>
          <div class="flex-1">
            <p class="text-sm font-medium text-gray-900 dark:text-gray-100">{notification.message}</p>
          </div>
          <button
            on:click={() => notification = null}
            class="flex-shrink-0 text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 transition-colors"
            aria-label="Close notification"
          >
            <svg class="w-4 h-4" 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"></path>
            </svg>
          </button>
        </div>
      </div>
    </div>
  {/if}

  <!-- View Toggle -->
  <div class="flex justify-end mb-4">
    <div class="flex bg-gray-100 dark:bg-gray-700 rounded-lg p-1">
      <button
        class="px-4 py-2 rounded-md text-sm font-medium transition-colors {view === 'cards' ? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-gray-200 shadow-sm' : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'}"
        on:click={() => view = 'cards'}
      >
        📄 Cards
      </button>
      <button
        class="px-4 py-2 rounded-md text-sm font-medium transition-colors {view === 'table' ? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-gray-200 shadow-sm' : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'}"
        on:click={() => view = 'table'}
      >
        📊 Table
      </button>
    </div>
  </div>

  {#if view === 'cards'}
    <!-- Cards View -->
    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
      {#each pots as pot (pot.id)}
        <div class="group relative bg-white dark:bg-gray-800 rounded-2xl shadow-lg hover:shadow-2xl transition-all duration-300 transform hover:-translate-y-1 border border-gray-100 dark:border-gray-700 overflow-hidden cursor-pointer" on:click={() => openPlantDetail(pot)} on:keydown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openPlantDetail(pot); } }} role="button" tabindex="0" aria-label="View {pot.name} plant details">
          <!-- Status indicator ribbon -->
          <div class="absolute top-0 right-0 z-10">
            <div class="{getStatusBadgeClass(pot)} px-3 py-1 rounded-bl-xl text-xs font-semibold shadow-sm">
              {getStatusText(pot)}
            </div>
          </div>

          <!-- Plant photo or placeholder -->
          <div class="relative h-48 bg-gradient-to-br from-green-100 to-blue-100 dark:from-gray-700 dark:to-gray-600 flex items-center justify-center overflow-hidden">
            {#if pot.photo}
              <img
                src={pot.photo}
                alt="{pot.name} plant"
                class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
              />
              <div class="absolute inset-0 bg-gradient-to-t from-black/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
            {:else}
              <div class="text-6xl opacity-60 group-hover:scale-110 transition-transform duration-300">
                🌱
              </div>
            {/if}
          </div>

          <!-- Card content -->
          <div class="p-6">
            <div class="flex justify-between items-start mb-4">
              <div class="flex-1">
                <h3 class="font-bold text-xl text-gray-900 dark:text-gray-100 mb-1 group-hover:text-green-600 dark:group-hover:text-green-400 transition-colors">
                  {pot.name}
                </h3>
                <p class="text-sm text-gray-600 dark:text-gray-400 font-medium">
                  {pot.plantType}
                </p>
              </div>
              <div class="flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                <button
                  class="w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-900 text-blue-600 dark:text-blue-400 hover:bg-blue-200 dark:hover:bg-blue-800 flex items-center justify-center transition-colors"
                  on:click|stopPropagation={() => editPot(pot)}
                  title="Edit plant"
                >
                  ✏️
                </button>
                <button
                  class="w-8 h-8 rounded-full bg-red-100 dark:bg-red-900 text-red-600 dark:text-red-400 hover:bg-red-200 dark:hover:bg-red-800 flex items-center justify-center transition-colors"
                  on:click|stopPropagation={() => removePot(pot.id)}
                  title="Remove plant"
                >
                  🗑️
                </button>
              </div>
            </div>

            <!-- Plant details -->
            <div class="space-y-3 mb-6">
              <div class="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">
                <span class="text-blue-500">⏰</span>
                <span class="font-medium">Water every {pot.wateringFrequency} days</span>
              </div>
              <div class="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">
                <span class="text-green-500">💧</span>
                <span>Last watered: {pot.lastWatered.toLocaleDateString()}</span>
              </div>
              {#if pot.notes}
                <div class="flex gap-2 text-sm text-gray-500 dark:text-gray-500 italic bg-gray-50 dark:bg-gray-700 rounded-lg p-3">
                  <span>📝</span>
                  <span>{pot.notes}</span>
                </div>
              {/if}
            </div>

            <!-- Water now button -->
            {#if canWater(pot.id)}
              <button
                class="w-full bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white py-3 px-4 rounded-xl font-semibold transition-all duration-200 shadow-lg hover:shadow-xl transform hover:scale-105 flex items-center justify-center gap-2"
                on:click|stopPropagation={() => waterPot(pot.id)}
              >
                <span class="text-lg">💧</span>
                <span>Water Now</span>
              </button>
            {:else}
              <div class="w-full bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 py-3 px-4 rounded-xl font-semibold flex items-center justify-center gap-2 border-2 border-dashed border-gray-300 dark:border-gray-600">
                <span class="text-lg">⏳</span>
                <span>Watered recently ({formatCooldownTime(getCooldownTimeRemaining(pot.id))})</span>
              </div>
            {/if}
          </div>

          <!-- Decorative elements -->
          <div class="absolute top-4 left-4 w-2 h-2 bg-green-400 rounded-full opacity-60 group-hover:opacity-100 transition-opacity"></div>
          <div class="absolute bottom-4 right-4 w-1 h-1 bg-blue-400 rounded-full opacity-40 group-hover:opacity-80 transition-opacity"></div>
        </div>
      {/each}
    </div>
  {:else}
    <!-- Table View -->
    <div class="overflow-x-auto bg-white dark:bg-gray-800 rounded-lg shadow">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50 dark:bg-gray-700">
          <tr>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Plant</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Type</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Frequency</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Last Watered</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Status</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Actions</th>
          </tr>
        </thead>
        <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-600">
          {#each pots as pot (pot.id)}
            <tr class="hover:bg-gray-50 dark:hover:bg-gray-700">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  {#if pot.photo}
                    <img
                      src={pot.photo}
                      alt="{pot.name} plant"
                      class="w-10 h-10 object-cover rounded-lg border border-gray-200 dark:border-gray-600 mr-3"
                    />
                  {/if}
                  <div>
                    <div class="text-sm font-medium text-gray-900 dark:text-gray-200">{pot.name}</div>
                    {#if pot.notes}
                      <div class="text-sm text-gray-500 dark:text-gray-400 italic">{pot.notes}</div>
                    {/if}
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-200">{pot.plantType}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-200">Every {pot.wateringFrequency} days</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-200">{pot.lastWatered.toLocaleDateString()}</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full {getStatusBadgeClass(pot)}">
                  {getStatusText(pot)}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <div class="flex gap-2">
                  <button
                    class="text-blue-600 hover:text-blue-900 p-1"
                    on:click|stopPropagation={() => waterPot(pot.id)}
                    title="Water now"
                  >
                    💧
                  </button>
                  <button
                    class="text-blue-600 hover:text-blue-900 p-1"
                    on:click={() => editPot(pot)}
                    title="Edit pot"
                  >
                    ✏️
                  </button>
                  <button
                    class="text-red-600 hover:text-red-900 p-1"
                    on:click={() => removePot(pot.id)}
                    title="Remove pot"
                  >
                    🗑️
                  </button>
                </div>
              </td>
            </tr>
          {/each}
        </tbody>
      </table>
    </div>
  {/if}
{/if}

<!-- Plant Detail Modal -->
<PlantDetailModal
  {isModalOpen}
  pot={selectedPot}
  canWaterPlant={selectedPot ? canWater(selectedPot.id) : true}
  cooldownTimeRemaining={selectedPot ? getCooldownTimeRemaining(selectedPot.id) : 0}
  on:close={closePlantDetail}
  on:watered={(e) => {
    // Update cooldown tracking when modal waters a plant
    lastWateringTimes.set(e.detail.potId, Date.now());
    showNotification(`Successfully watered ${e.detail.potName}!`, 'success');
  }}
/>