defmodule ZoeyscomputerWeb.GistLive.FormComponent do
  use ZoeyscomputerWeb, :live_component

  import ZoeyscomputerWeb.GistLive.Select

  alias Zoeyscomputer.Gists

  @impl true
  def render(assigns) do
    ~H"""
    <div>
      <.header>
        <%= @title %>
        <:subtitle>Use this form to manage gist records in your database.</:subtitle>
      </.header>
      <.simple_form
        for={@form}
        id="gist-form"
        phx-target={@myself}
        phx-change="validate"
        phx-submit="save"
      >
        <.input field={@form[:title]} type="text" label="Title" />
        <.input field={@form[:desc]} type="textarea" label="Description" />
        <.input field={@form[:code]} type="textarea" label="Code" />
        <.select
          id="lang-select"
          form={@form}
          field={:lang}
          label="Language"
          options={[
            {"JavaScript", "javascript"},
            {"Python", "python"},
            {"Elixir", "elixir"},
            {"Ruby", "ruby"},
            {"Rust", "rust"}
          ]}
        />
        <:actions>
          <.button phx-disable-with="Saving...">Save Gist</.button>
        </:actions>
      </.simple_form>
    </div>
    """
  end

  @impl true
  def update(%{gist: gist} = assigns, socket) do
    {:ok,
     socket
     |> assign(assigns)
     |> assign_new(:form, fn ->
       to_form(Gists.change_gist(gist))
     end)}
  end

  @impl true
  def handle_event("validate", %{"gist" => gist_params}, socket) do
    changeset = Gists.change_gist(socket.assigns.gist, gist_params)
    {:noreply, assign(socket, form: to_form(changeset, action: :validate))}
  end

  def handle_event("save", %{"gist" => gist_params}, socket) do
    save_gist(socket, socket.assigns.action, gist_params)
  end

  # Updated to use lang instead of language
  def handle_event("change", %{"value" => value}, socket) do
    current_params = socket.assigns.form.params || %{}
    updated_params = Map.put(current_params, "lang", value)
    changeset = Gists.change_gist(socket.assigns.gist, updated_params)
    {:noreply, assign(socket, form: to_form(changeset, action: :validate))}
  end

  defp save_gist(socket, :edit, gist_params) do
    case Gists.update_gist(socket.assigns.gist, gist_params) do
      {:ok, gist} ->
        notify_parent({:saved, gist})

        {:noreply,
         socket
         |> put_flash(:info, "Gist updated successfully")
         |> push_patch(to: socket.assigns.patch)}

      {:error, %Ecto.Changeset{} = changeset} ->
        {:noreply, assign(socket, form: to_form(changeset))}
    end
  end

  defp save_gist(socket, :new, gist_params) do
    case Gists.create_gist(socket.assigns.current_user, gist_params) do
      {:ok, gist} ->
        notify_parent({:saved, gist})

        {:noreply,
         socket
         |> put_flash(:info, "Gist created successfully")
         |> push_patch(to: socket.assigns.patch)}

      {:error, %Ecto.Changeset{} = changeset} ->
        IO.inspect(changeset)
        {:noreply, assign(socket, form: to_form(changeset))}
    end
  end

  defp notify_parent(msg), do: send(self(), {__MODULE__, msg})
end
