defmodule TodoitWeb.Live.Index do
  use TodoitWeb, :live_view

  @impl true
  def mount(_params, _session, socket) do
    tasks = Todoit.Todo.list_todos!( )

    socket =
      socket
      |> assign(:tasks, tasks)
      |> assign(:current_filter, "all")

    {:ok, socket}
  end
  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app {assigns}>
      <.accordion id="example-11" space="large">
        <:item title="Show & Filter Tasks">
          <.flash kind={:info} flash={@flash} title="Success!" />
          <.flash kind={:error} flash={@flash} title="Error!" />
          <Cinder.Table.table
            resource={Todoit.Todo.Task}
            row_click={fn task -> JS.navigate(~p"/tasks/#{task.id}/edit") end}
          >
            <:col :let={task} field="title" filter sort>{task.title}</:col>
            <:col :let={task} field="description" filter sort>{task.description}</:col>
            <:col :let={task} field="inserted_at" filter>{task.inserted_at}</:col>
            <:col :let={task} field="updated_at" sort>{task.updated_at}</:col>
            <:col :let={task} label="Tools">
              <.button
                icon="hero-trash"
                color="danger"
                phx-click="delete"
                phx-value-id={task.id}
              >
                Delete
              </.button>
            </:col>
          </Cinder.Table.table>
        </:item>
      </.accordion>

      <.h1>Manage Tasks</.h1>


    <div class="grid grid-cols-3 gap-4">
      <div :for={task <- @tasks} :if={task.done == false} class="card w-96 bg-base-100 card-lg shadow-sm">
        <div class="card-body">
          <h2 class="card-title"><%= task.title %></h2>
          <p><%= task.description %></p>

          <span> Created at <.badge size="small" variant="bordered" color="primary" rounded="full">{Calendar.strftime(task.inserted_at, "%d %B %Y, %H:%M")}</.badge> </span>
          <div class="flex justify-between items-center">
            <.button
              size="small"
              color={if task.done, do: "success", else: "secondary"}
              phx-click="toggle_done"
              phx-value-id={task.id}
            >
              <%= if task.done, do: "✓ Done", else: "○ Pending" %>
            </.button>

            <div class="card-actions">
              <button
                class="btn btn-warning btn-sm"
                phx-click={JS.navigate(~p"/tasks/#{task.id}/edit")}
              >
                Edit
              </button>

              <button
                class="btn btn-error btn-sm"
                phx-click="delete"
                phx-value-id={task.id}
              >
                Delete
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <.accordion id="example-12" space="large">
      <:item title="Completed Tasks">
    <div class="grid grid-cols-3 gap-4">
      <div :for={task <- @tasks} :if={task.done == true} class="card w-96 bg-base-100 card-lg shadow-sm">
        <div class="card-body">
          <h2 class="card-title"><%= task.title %></h2>
          <p><%= task.description %></p>

          <div class="flex justify-between items-center">
            <.button
              size="small"
              color={if task.done, do: "success", else: "secondary"}
              phx-click="toggle_done"
              phx-value-id={task.id}
            >
              <%= if task.done, do: "✓ Done", else: "○ Pending" %>
            </.button>

            <div class="card-actions">
              <button
                class="btn btn-warning btn-sm"
                phx-click={JS.navigate(~p"/tasks/#{task.id}/edit")}
              >
                Edit
              </button>

              <button
                class="btn btn-error btn-sm"
                phx-click="delete"
                phx-value-id={task.id}
              >
                Delete
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
      </:item>
      </.accordion>
      </Layouts.app>
    """
  end




  @impl true
  def handle_event("toggle_done", %{"id" => id}, socket) do
    task = Todoit.Todo.get_todo!(id)

    case Todoit.Todo.update_todo(task, %{done: !task.done}) do
      {:ok, _updated} ->
        {:noreply,
         socket
         |> put_flash(:info, "Task updated")
         |> assign(:tasks, Todoit.Todo.list_todos())}

      {:error, _} ->
        {:noreply, put_flash(socket, :error, "Could not update task")}
    end
  end





  @impl true
  def handle_event("delete", %{"id" => id}, socket) do
    task = Todoit.Todo.get_todo!(id)

    case Todoit.Todo.delete_todo(task) do
      {:ok, _} ->
        {:noreply,
         socket
         |> put_flash(:info, "Task deleted successfully")
         |> assign(:tasks, Todoit.Todo.list_todos!(
           load: [:display_title, :is_incomplete, :status, :date_category]
         ))}

      {:error, _} ->
        {:noreply, put_flash(socket, :error, "Could not delete task")}
    end
  end
end
