(ns todo.widgets.todo-list
  (:require
   ["package:flutter/material.dart" :as m]
   [cljd.flutter :as f]
   [todo.state :as state]
   [todo.db :as db]
   [todo.widgets.todo-item :as todo-item]
   [todo.widgets.empty-state :as empty-state]))

(defn todo-list-widget [todos]
  (if (empty? todos)
    (empty-state/empty-state-widget)
    (m/ListView.builder
      .padding (m/EdgeInsets.only .bottom 80)
      .itemCount (count todos)
      .itemBuilder
      (f/build [idx]
        (let [todo (nth todos idx)]
          (m/Dismissible
            .key (m/ValueKey (:id todo))
            .direction m/DismissDirection.endToStart
            .background
            (m/Container
              .alignment m/Alignment.centerRight
              .padding (m/EdgeInsets.only .right 20)
              .color m/Colors.red
              .child (m/Icon m/Icons.delete .color m/Colors.white))
            .onDismissed (fn [_]
                           (let [id (:id todo)]
                             (state/delete-todo! id)
                             (db/delete-todo-db! id)))
            .child (todo-item/todo-item-widget todo)))))))
