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

  let pots: FlowerPot[] = [];
  let view: 'cards' | 'table' = 'cards';

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

  function waterPot(id: string) {
    flowerPots.water(id);
  }

  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
  }
</script>

{#if pots.length === 0}
  <div class=\"text-center py-8 text-gray-500\">
    <p class=\"text-lg mb-2\">No flower pots yet</p>
    <p>Add your first pot to get started!</p>
  </div>
{:else}
  <!-- View Toggle -->
  <div class=\"flex justify-end mb-4\">
    <div class=\"flex bg-gray-100 rounded-lg p-1\">
      <button
        class=\"px-4 py-2 rounded-md text-sm font-medium transition-colors {view === 'cards' ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-600 hover:text-gray-900'}\"
        on:click={() => view = 'cards'}
      >
        📄 Cards
      </button>
      <button
        class=\"px-4 py-2 rounded-md text-sm font-medium transition-colors {view === 'table' ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-600 hover:text-gray-900'}\"
        on:click={() => view = 'table'}
      >
        📊 Table
      </button>
    </div>
  </div>

  {#if view === 'cards'}
    <!-- Cards View -->
    <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">
      {#each pots as pot (pot.id)}
        <div class=\"border rounded-lg p-4 {getStatusColor(pot)}\">
          <div class=\"flex justify-between items-start mb-3\">
            <div class=\"flex items-start gap-3 flex-1\">
              {#if pot.photo}
                <img
                  src={pot.photo}
                  alt=\"{pot.name} plant\"
                  class=\"w-16 h-16 object-cover rounded-lg border border-gray-200 flex-shrink-0\"
                />
              {/if}
              <div class=\"flex-1\">
                <h3 class=\"font-semibold text-lg\">{pot.name}</h3>
                <p class=\"text-sm opacity-75\">{pot.plantType}</p>
              </div>
            </div>
            <div class=\"flex gap-1\">
              <button
                class=\"text-blue-600 hover:text-blue-800 p-1\"
                on:click={() => editPot(pot)}
                title=\"Edit pot\"
              >
                ✏️
              </button>
              <button
                class=\"text-red-600 hover:text-red-800 p-1\"
                on:click={() => removePot(pot.id)}
                title=\"Remove pot\"
              >
                🗑️
              </button>
            </div>
          </div>

          <div class=\"space-y-2 mb-3\">
            <p class=\"text-sm\">
              <span class=\"font-medium\">Frequency:</span> Every {pot.wateringFrequency} days
            </p>
            <p class=\"text-sm\">
              <span class=\"font-medium\">Last watered:</span> {pot.lastWatered.toLocaleDateString()}
            </p>
            <p class=\"text-sm font-medium\">
              {getStatusText(pot)}
            </p>
            {#if pot.notes}
              <p class=\"text-sm italic\">{pot.notes}</p>
            {/if}
          </div>

          <button
            class=\"w-full bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded transition-colors\"
            on:click={() => waterPot(pot.id)}
          >
            💧 Water Now
          </button>
        </div>
      {/each}
    </div>
  {:else}
    <!-- Table View -->
    <div class=\"overflow-x-auto bg-white rounded-lg shadow\">
      <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\">Plant</th>
            <th class=\"px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider\">Type</th>
            <th class=\"px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider\">Frequency</th>
            <th class=\"px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider\">Last Watered</th>
            <th class=\"px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider\">Status</th>
            <th class=\"px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider\">Actions</th>
          </tr>
        </thead>
        <tbody class=\"bg-white divide-y divide-gray-200\">
          {#each pots as pot (pot.id)}
            <tr class=\"hover:bg-gray-50\">
              <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 mr-3\"
                    />
                  {/if}
                  <div>
                    <div class=\"text-sm font-medium text-gray-900\">{pot.name}</div>
                    {#if pot.notes}
                      <div class=\"text-sm text-gray-500 italic\">{pot.notes}</div>
                    {/if}
                  </div>
                </div>
              </td>
              <td class=\"px-6 py-4 whitespace-nowrap text-sm text-gray-900\">{pot.plantType}</td>
              <td class=\"px-6 py-4 whitespace-nowrap text-sm text-gray-900\">Every {pot.wateringFrequency} days</td>
              <td class=\"px-6 py-4 whitespace-nowrap text-sm text-gray-900\">{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={() => 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}