defmodule RefugeWeb.JobsLive do
  use RefugeWeb, :live_view

  @impl true
  def mount(_params, _session, socket) do
    jobs = [
      %{id: 1, name: "Acme Corp", title: "Software Engineer", description: "Build amazing software"},
      %{id: 2, name: "Globex", title: "Frontend Developer", description: "Create beautiful UIs"},
      %{id: 3, name: "Initech", title: "Backend Engineer", description: "Design scalable systems"},
      %{id: 4, name: "Umbrella Corp", title: "DevOps Engineer", description: "Manage cloud infrastructure"},
      %{id: 5, name: "Stark Industries", title: "AI Researcher", description: "Develop cutting-edge AI solutions"}
    ]
    
    socket =
      socket
      |> assign(:jobs, jobs)
      |> assign(:search_query, "")
      |> assign(:filtered_jobs, jobs)
    
    {:ok, socket}
  end

  @impl true
  def handle_event("search", %{"query" => query}, socket) do
    filtered_jobs = 
      socket.assigns.jobs
      |> Enum.filter(fn job -> 
        job_text = job.name <> job.title <> job.description
        String.contains?(String.downcase(job_text), String.downcase(query))
      end)

    {:noreply, assign(socket, search_query: query, filtered_jobs: filtered_jobs)}
  end

  @impl true
  def render(assigns) do
    ~H"""
    <div class="mx-auto max-w-4xl px-4 py-8">
      <h1 class="text-3xl font-bold mb-8">Jobs</h1>
      
      <form phx-submit="search" class="mb-8">
        <div class="flex gap-2">
          <input
            type="text"
            name="query"
            value={@search_query}
            placeholder="Search jobs..."
            class="flex-1 rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
          />
          <button
            type="submit"
            class="rounded-md bg-indigo-600 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
          >
            Search
          </button>
        </div>
      </form>
      
      <div class="divide-y divide-gray-200">
        <%= for job <- @filtered_jobs do %>
          <div class="py-4">
            <div class="flex items-center justify-between">
              <div>
                <h2 class="text-xl font-semibold text-gray-900"><%= job.title %></h2>
                <p class="mt-1 text-gray-600"><%= job.name %></p>
              </div>
              <a
                href={"/jobs/#{job.id}"}
                class="rounded-md bg-indigo-50 px-3.5 py-2.5 text-sm font-semibold text-indigo-600 shadow-sm hover:bg-indigo-100"
              >
                View Job
              </a>
            </div>
            <p class="mt-2 text-gray-500"><%= job.description %></p>
          </div>
        <% end %>
      </div>
    </div>
    """
  end
end
