module Public
  class ClubMatchesController < WebBaseController
    before_action :require_login!
    before_action :set_club
    before_action :load_schedulable_teams
    before_action :require_any_schedulable_team!

    def new
      @match = default_match_for_form
      @selected_team = resolve_selected_team
    end

    def create
      @selected_team = @schedulable_teams.find { |t| t.id.to_s == params[:team_id].to_s }
      unless @selected_team
        @match = default_match_for_form
        flash.now[:alert] = "Seleziona una squadra valida."
        return render :new, status: :unprocessable_entity
      end

      @match = @selected_team.matches.create!(
        match_params.merge(sport: @selected_team.sport, sets_to_win: 3)
      )
      redirect_to public_live_index_path(club_id: @club.id),
                  notice: "Partita programmata: #{@selected_team.name} vs #{@match.opponent_name}."
    rescue ActiveRecord::RecordInvalid => e
      @match = @selected_team.matches.build(match_params)
      flash.now[:alert] = e.record.errors.full_messages.join(", ")
      render :new, status: :unprocessable_entity
    end

    private

    def set_club
      @club = Club.find(params[:club_id])
    end

    def load_schedulable_teams
      @schedulable_teams = current_user.schedulable_teams_for(@club)
      @club_admin = @club.owned_by?(current_user)
    end

    def require_any_schedulable_team!
      return if @schedulable_teams.any?

      redirect_to public_live_index_path(club_id: @club.id),
                  alert: "Non hai permessi per programmare partite in questa società."
    end

    def resolve_selected_team
      if params[:team_id].present?
        @schedulable_teams.find { |t| t.id.to_s == params[:team_id].to_s }
      end || @schedulable_teams.first
    end

    def default_match_for_form
      team = resolve_selected_team
      Match.new(
        sport: team&.sport || @club.sport,
        sets_to_win: 3,
        scheduled_at: default_scheduled_at
      )
    end

    def match_params
      p = params.require(:match).permit(:opponent_name, :location, :scheduled_at)
      p[:scheduled_at] = parse_scheduled_at(p[:scheduled_at]) if p[:scheduled_at].present?
      p
    end

    def parse_scheduled_at(value)
      raw = value.to_s.strip
      return nil if raw.blank?

      Time.zone.strptime(raw, "%Y-%m-%dT%H:%M")
    rescue ArgumentError
      Time.zone.parse(raw)
    end

    def default_scheduled_at
      t = Time.current + 2.hours
      Time.zone.local(t.year, t.month, t.day, t.hour, 0, 0)
    end
  end
end
