defmodule DerivantesWeb.DerivantesLive do
  use DerivantesWeb, :live_view
  use Phoenix.Component
  import Ecto.Query

  def mount(_params, _session, socket) do
	filters = to_form(%{}, as: "filters")
	{:ok,
  	socket
  	|> assign(studies: get_studies(socket, %{}))
  	|> assign(filters: filters)
	}
  end

  def render(assigns) do
	~H"""
  	<div>
      	<div class="estudio_patientname">
				<h1>Bienvenido, <%= @current_user.email |> String.split("@") |> List.first %> </h1>
				<p>Para ver un estudio haga click en el icono de Informe o de Imágenes.</p>
      	</div>
      	<div class="px-5 pb-5">
        	<.simple_form
          	for={@filters}
          	id="filters"
          	phx-update="ignore"
          	phx-submit="filter_study"
						class="flex items-stretch"
        	>
          	<.input field={@filters[:dni]} type="text" placeholder="Documento del paciente"/>
          	<.input field={@filters[:nombre]} type="text" placeholder="Nombre del paciente"/>
          	<.input field={@filters[:apellido]} type="text" placeholder="Apellido del paciente"/>
          	<.input field={@filters[:fecha]} type="date"/>

						<br>
          	<:actions>
            	<.button class="w-full">
								<i class="fa fa-search" aria-hidden="true"></i>
							</.button>
          	</:actions>
        	</.simple_form>
      	</div>
    	<%= if length(@studies) > 0 do %>
      	<div class="estudio_container">
        	<div class="estudio_details">
          	<p>Estudios</p>
        	</div>
        	<div class="estudio_icons">
          	<p>Informe</p>
          	<p>Imágenes</p>
        	</div>
      	</div>
      	<%= for study <- @studies do %>
        	<div class="estudio_container">
          	<div class="estudio_details">
            	<p><b>Fecha y hora:</b> <%= format_date(study.fecha) %> - <%= format_hour(study.hora) %></p>
            	<p><b>DNI:</b> <%= study.dni %></p>
            	<p><b>Accession N°</b> <%= study.accession %></p>
            	<p><b>Matricula derivante</b> <%= @current_user.matricula %></p>

          	</div>
          	<div class="estudio_icons">
            	<%= case {study.modality, study.esteco, study.estrx} do %>
              	<% {"US", "F", _} -> %>
              	<a href={"https://sga.sanatorio-americano.com.ar/diagnostico/impeco.asp?id=#{study.accession}"} target="_blank" style="color: #297177">
                	<i class="fa-regular fa-file-lines fa-3x" style="color: #297177"></i>
              	</a>
              	<% {modality, _, "E"} when modality != "US" -> %>
              	<a href={"https://ed.sanatorio-americano.com.ar/cgi-bin/minisite.bf/pdfonthefly/#{study.accession}"} target="_blank" style="color: #297177">
                	<i class="fa-regular fa-file-lines fa-3x" style="color: #297177"></i>
              	</a>
              	<% _ -> %>
                	<i class="fa-solid fa-file-circle-question fa-3x" style="color: #DCDCDC"></i>
            	<% end %>
            	<%= if study.modality != "US" do %>
            	<a href={"https://imagenes.sanatorio-americano.com.ar/portal/Default.aspx?user_name=urlusr&password=1nt3gr4c10n$$$&accession_number=#{study.accession}"} target="_blank" style="color: #297177">
              	<i class="fa-solid fa-file-circle-check fa-3x" style="color: #297177"></i>
            	</a>
            	<% else %>
              	<i class="fa-solid fa-file-circle-question fa-3x" style="color: #DCDCDC"></i>
            	<% end %>
          	</div>
        	</div>
      	<% end %>
    	<% else %>
      	<div>
        	<h1>
          	No hay estudios para mostrar
        	</h1>
      	</div>
    	<% end %>
  	</div>

	"""
  end

  def format_date(date_string) when is_binary(date_string) do
	   anio = String.slice(date_string, 0..3)
	   mes = String.slice(date_string, 4..5)
	   dia = String.slice(date_string, 6..7)
	   "#{dia}/#{mes}/#{anio}"
  end
  def format_hour(hour_string) when is_binary(hour_string) do
    hora = String.slice(hour_string, 0..1)
    minutos = String.slice(hour_string, 2..3)
    segundos = String.slice(hour_string, 4..6)
    "#{hora}:#{minutos}:#{segundos}"
  end

  def get_studies(socket, filter) do

  	keys = Map.keys(filter)
  	mat_filter = dynamic([vl], vl.matder == ^socket.assigns.current_user.matricula)
  	filter_conditions =
    	Enum.reduce(keys, mat_filter, fn v, filter_conditions ->
      	case v do
        	"dni" ->
          	if(filter["dni"] != "") do
							dni_with_du = "DU" <> filter["dni"]
            	dynamic([vl], vl.tipo_documento == ^dni_with_du and ^filter_conditions)
          	else
            	filter_conditions
          	end
        	"nombre" ->
          	if(filter["nombre"] != "") do
            	dynamic([vl], vl.patientfirstname == ^filter["nombre"] and ^filter_conditions)
          	else
            	filter_conditions
          	end
        	"apellido" ->
          	if(filter["apellido"] != "") do
            	dynamic([vl], vl.patientlastname == ^filter["apellido"] and ^filter_conditions)
          	else
            	filter_conditions
          	end
						"fecha" ->
          	if(filter["fecha"] != "") do
            	dynamic([vl], vl.start_date == ^String.replace(filter["fecha"], "-", "") and ^filter_conditions)
          	else
            	filter_conditions
          	end
        	_ ->
          	filter_conditions
      	end
    	end)


		query = from vl in "V_LISTAINGRESOS",
  		select: %{
  	  	idstudy: field(vl, :ID),
  	  	estrx: field(vl, :ESTRX),
  	  	esteco: field(vl, :ESTECO),
# 	  	desc: field(vl, :PROD_DESC),
  	  	hora: field(vl, :START_TIME),
  	  	fecha: field(vl, :START_DATE),
  	  	modality: field(vl, :MODALITY),
  	  	dni: field(vl, :TIPO_DOCUMENTO),
  	  	lastname: field(vl, :PATIENTLASTNAME),
  	  	accession: field(vl, :ACCESSIONNUMBER),
  	  	patientname: field(vl, :PATIENTFIRSTNAME)
  		},
  		where: ^filter_conditions,
  		order_by: [desc: field(vl, :START_DATE)]
  		estudios = Derivantes.TdsRepo.all(query)
  		estudios
  end

  def handle_event(event, params, socket) do
  	case event do
    	"filter_study" ->
      	studies = get_studies(socket, params["filters"])
      	{:noreply,
      	socket
      	|> assign(studies: studies)
    	}
  	end
  end
end
