defmodule TodoitWeb.Live.Form do
  use TodoitWeb, :live_view
  # use TodoitWeb.Components.MishkaComponents
  # use Phoenix.Component
  # alias Todoit.Todo.Task
  # alias Todoit.Todo

  @impl true
  def mount(%{"id" => task_id}, _session, socket) do
    todo = Todoit.Todo.get_todo!(task_id)

    form = Todoit.Todo.form_to_update_todo(todo)

    socket =
      socket
      |> assign(:todo, todo)
      |> assign(:form, to_form(form))
      |> assign(:page_title, "Edit Task")

    {:ok, socket}
  end

  @impl true
  def mount(_params, _session, socket) do
    form =
      Todoit.Todo.form_to_create_todo()
      |> to_form()

    socket =
      socket
      |> assign(:form, form)
      |> assign(:page_title, "New Task")

    {:ok, socket}
  end

  @impl true
  def handle_event("validate", %{"form" => form_data}, socket) do
    form = AshPhoenix.Form.validate(socket.assigns.form, form_data)
    {:noreply, assign(socket, form: form)}
  end

  @impl true
  def handle_event("save", %{"form" => form_data}, socket) do
    params = form_data

    case AshPhoenix.Form.submit(socket.assigns.form, params: params) do
      {:ok, _todo} ->
        {:noreply,
         socket
         |> put_flash(:info, "Task saved successfully")
         |> push_navigate(to: ~p"/tasks")}

      {:error, form} ->
        IO.inspect(form.errors, label: "FORM ERRORS")

        {:noreply,
         socket
         |> put_flash(:error, "Could not save form")
         |> assign(:form, form)}
    end
  end

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app {assigns}>
    <.flash kind={:info} flash={@flash} title="Success!"/>
    <.flash kind={:error} flash={@flash} title="Error!"/>
    

    <.form_wrapper
      for={@form}
      id="todo"
      phx-change="validate"
      phx-submit="save"
      class="space-y-5"
    >
      <.text_field
        field={@form[:title]}
        description="Write your todo title"
        label="Title"
        placeholder="To make my tomorrow plan"
        variant="base"
      />

      <.textarea_field
        field={@form[:description]}
        label="Description"
        placeholder="Task description"
      />

      <div class="py-8">
        <.toggle_field field={@form[:done]} label="Done?" phx-debounce="300"/>
      </div>

      <:actions>
        <.button type="submit" variant="inverted" color="success">Save</.button>
      </:actions>
    </.form_wrapper>

    </Layouts.app>
    """
  end
end
